如何绑定到静态属性编程? [英] How to bind to static property programmatically?

查看:110
本文介绍了如何绑定到静态属性编程?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何绑定到静态属性编程?我可以在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 名称 TextProperty $ C>。

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();

这篇关于如何绑定到静态属性编程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆