0

在 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);
}

...但是 MAN 这让我很恼火,我不得不求助于创建动态 XAML,然后解析它!啊!!但是,嘿......它的工作原理。

我不得不认为有一个更简单的方法!那是什么?

4

1 回答 1

1

通过 xaml paserer创建一个PropertyPath不同于Binding. 所以你应该使用下面的代码来让它工作。

var binding = new Binding() {
    Path = new PropertyPath(typeof(StaticClass).GetProperty(nameof(StaticClass.StaticProperty))),
};
于 2018-09-08T10:40:34.050 回答