代码之家  ›  专栏  ›  技术社区  ›  Mark A. Donohoe

如何设置从代码隐藏到静态属性的绑定?(WPF 4.5+)

  •  0
  • Mark A. Donohoe  · 技术社区  · 7 年前

    在XAML中,设置到静态属性的绑定很简单。。。

    <TextBlock Text="{Binding Path=(foo:StaticClass.StaticProperty)}" />
    

    我试过以下方法:

    var b = new Binding(){
        Path = new PropertyPath(StaticClass.StaticProperty)
    };
    
    var b = new Binding(){
        Path = new PropertyPath("StaticClass.StaticProperty")
    };
    
    var b = new Binding(){
        Source = StaticClass,
        Path   = new PropertyPath("StaticProperty")
    };
    

    ……但以上都不管用。

    var binding = new Binding(){
        Source = StaticClass.StaticProperty
    };
    

    public static Binding CreateStaticBinding(Type classType, string propertyName){
    
        var xaml = $@"
            <Binding
                xmlns    = ""http://schemas.microsoft.com/winfx/2006/xaml/presentation""
                xmlns:is = ""clr-namespace:{$"{classType.Namespace};assembly={classType.Assembly.GetName().Name}"}""
                Path=""(is:{classType.Name}.{propertyName})"" />";
    
        return (Binding)System.Windows.Markup.XamlReader.Parse(xaml);
    }
    

    …但这让我很恼火,我不得不创建动态XAML,然后解析它!啊!!但是嘿。。。它起作用了。

    我想还有更简单的办法!那是什么?

    1 回复  |  直到 7 年前
        1
  •  1
  •   Mark A. Donohoe    7 年前

    创建 PropertyPath 由xaml编写的paserer与 Binding

    var binding = new Binding() {
        Path = new PropertyPath(typeof(StaticClass).GetProperty(nameof(StaticClass.StaticProperty))),
    };
    
    推荐文章