如何绑定到静态属性编程?我可以在C#中使用,使
How to bind to static property programmatically? What can I use in C# to make
{Binding Source={x:Static local:MyClass.StaticProperty}}
更新:是有可能做OneWayToSource结合?据我所知,双向是不可能的,因为有对静态对象没有更新事件(至少在.NET 4中)。我不能实例化对象,因为它是静态的。
Update: is it possible to do OneWayToSource binding? I understand that TwoWay is not possible because there are no update events on static objects (at least in .NET 4). I cannot instantiate object because it is static.
推荐答案
单向绑定的
OneWay binding
让我们假设你有类国家
与静态属性名称
。
Let's assume that you have class Country
with static property Name
.
public class Country
{
public static string Name { get; set; }
}
和现在你要绑定的TextBlock 。
And now you want binding property Name
to TextProperty
of TextBlock
.
Binding binding = new Binding();
binding.Source = Country.Name;
this.tbCountry.SetBinding(TextBlock.TextProperty, binding);
更新:双向绑定的
Update: TwoWay binding
国家
类看起来是这样的:
public static class Country
{
private static string _name;
public static string Name
{
get { return _name; }
set
{
_name = value;
Console.WriteLine(value); /* test */
}
}
}
,现在我们要这个属性名称
结合文本框
,这样:
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);
如果你想更新的目标,你必须使用 BindingEx pression
及功能 UpdateTarget
:
If you want update target you must use BindingExpression
and function UpdateTarget
:
Country.Name = "Poland";
BindingExpression be = BindingOperations.GetBindingExpression(this.tbCountry, TextBox.TextProperty);
be.UpdateTarget();
相关推荐
最新文章