プログラムで静的プロパティにバインドする方法は?私はプログラムで静的プロパティにバインドする方法は?
{Binding Source={x:Static local:MyClass.StaticProperty}}
を更新するためにC#で使用することができます。は結合OneWayToSource行うには、それは可能ですか?静的オブジェクト(少なくとも.NET 4では)には更新イベントがないため、TwoWayは使用できません。静的なのでオブジェクトをインスタンス化できません。
プログラムで静的プロパティにバインドする方法は?私はプログラムで静的プロパティにバインドする方法は?
{Binding Source={x:Static local:MyClass.StaticProperty}}
を更新するためにC#で使用することができます。は結合OneWayToSource行うには、それは可能ですか?静的オブジェクト(少なくとも.NET 4では)には更新イベントがないため、TwoWayは使用できません。静的なのでオブジェクトをインスタンス化できません。
結合一方向のは、あなたが静的プロパティName
を持つクラスCountry
を持っていると仮定しましょう。
public class Country
{
public static string Name { get; set; }
}
そして今、あなたはTextBlock
のTextProperty
にプロパティName
を結合します。
Binding binding = new Binding();
binding.Source = Country.Name;
this.tbCountry.SetBinding(TextBlock.TextProperty, binding);
更新:双方向
Country
クラスを結合は次のようになります。
public static class Country
{
private static string _name;
public static string Name
{
get { return _name; }
set
{
_name = value;
Console.WriteLine(value); /* test */
}
}
}
そして今、我々はTextBox
に、このプロパティName
を結合たいので:
Binding binding = new Binding();
binding.Source = typeof(Country);
binding.Path = new PropertyPath(typeof(Country).GetProperty("Name"));
binding.Mode = BindingMode.TwoWay;
binding.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged;
this.tbCountry.SetBinding(TextBox.TextProperty, binding);
あなたがターゲットを更新したい場合は、BindingExpression
と機能UpdateTarget
を使用する必要があります。
Country.Name = "Poland";
BindingExpression be = BindingOperations.GetBindingExpression(this.tbCountry, TextBox.TextProperty);
be.UpdateTarget();
あなたは常に静的なものへのアクセスを提供するために、非静的クラスを書くことができます。
静的クラス:
namespace SO.Weston.WpfStaticPropertyBinding
{
public static class TheStaticClass
{
public static string TheStaticProperty { get; set; }
}
}
非静的クラスは、静的プロパティへのアクセスを提供します。
namespace SO.Weston.WpfStaticPropertyBinding
{
public sealed class StaticAccessClass
{
public string TheStaticProperty
{
get { return TheStaticClass.TheStaticProperty; }
}
}
}
バインディングは、単純です:
<Window x:Class="SO.Weston.WpfStaticPropertyBinding.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:SO.Weston.WpfStaticPropertyBinding"
Title="MainWindow" Height="350" Width="525">
<Window.Resources>
<local:StaticAccessClass x:Key="StaticAccessClassRes"/>
</Window.Resources>
<Grid>
<TextBlock Text="{Binding Path=TheStaticProperty, Source={StaticResource ResourceKey=StaticAccessClassRes}}" />
</Grid>
</Window>