簡體   English   中英

如何從代碼隱藏設置到靜態屬性的綁定? (WPF 4.5+)

[英]How do you set up a binding to a static property from code-behind? (WPF 4.5+)

在 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,然后解析它! 啊!! 但是,嘿......它的工作原理。

我不得不認為有一個更簡單的方法! 那是什么?

通過xaml paserer創建PropertyPathBinding構造函數不同。 因此,您應該使用下面的代碼來使其正常工作。

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

我需要更深入地解決這個問題並綁定到具有非私有類型的靜態屬性的嵌套屬性: Thread.CurrentThread.CurrentCulture.NativeNameThread.CurrentThread是 Thread 類的靜態屬性, CurrentCulture是 Thread 的實例屬性類, NativeName是 CultureInfo 類的實例屬性)。

在 XAML 綁定路徑中設置為:

<Window xmlns:threading="clr-namespace:System.Threading;assembly=mscorlib">
...
<TextBlock 
     Name="txtCulture" 
     Text="{Binding Path=(threading:Thread.CurrentThread).CurrentCulture.NativeName}" />

所以在代碼中我必須使用帶有路徑和參數的 PropertyPath 構造函數並像這樣編寫它(使用也適用於 DependencyProperties 的方法):

System.Reflection.PropertyInfo staticProperty = 
    typeof(Thread).GetProperty(nameof(Thread.CurrentThread));

var cultureBinding = new Binding
{
    Path = new PropertyPath("(0).CurrentCulture.NativeName", staticProperty)
};

txtCulture.SetBinding(TextBlock.TextProperty, cultureBinding);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM