如何在XAML绑定到一个静态属性?

如何在XAML绑定到一个静态属性?

问题描述:

我想不同类的静态属性绑定到文本属性TextBlock的,并能得到绑定工作,但有没有更新的Text属性时,静态属性的值已更改。我已阅读,因为属性是静态的,已经看到了许多建议使用依赖属性的解决方案我无法使用INotifyPropertyChanged的。我很新的C#和真的不知道如何使用依赖属性,但做了几个这似乎并没有,原因有两个工作的尝试。 1.我的静态属性定制getter和setter和2的静态属性是在一些静态方法使用,我无法弄清楚如何使用一个依赖属性,使工作。我不知道如何使用依赖属性时使用自定义的getter和setter或者如果这甚至可以做或如何后,我将其更改为一个依赖属性继续使用静态方法静态属性。

I am trying to bind a static property of a different class to the Text Property of a TextBlock and can get the binding to work, but there's is no update to the Text Property when the static property's value has changed. I have read that I cannot use INotifyPropertyChanged because the property is static and have seen a number of solutions that suggest to use a Dependency Property. I am very new to C# and do not really understand how to use Dependency Properties, but have made a couple of attempts which do not seem to work for two reasons. 1. My static property has custom getter and setter and 2. The static property is used in a number of static methods which I can't figure out how to make work using a Dependency Property. I do not know how to use a custom getter and setter when using a Dependency Property or if this can even be done or how to continue using the static property in static methods after I change it to a Dependency Property.

下面是当前code的静态属性:

Here is the current code for the static property:

public class Helper
{
    public static string Token
    {
        get
        {
            using (StreamReader streamReader = new StreamReader("Token.ini"))
            {
                return streamReader.ReadLine();
            }
        }
        set
        {
            using (StreamWriter streamWriter = new StreamWriter("Token.ini"))
            {
                streamWriter.WriteLine(value);
            }
        }
    }

public static MethodThatUsesToken(){}
public static OtherMethodThatUsesToken(){}

在这里,目前XAML为其工作,但不更新绑定:

And here the current XAML for the binding which works but doesn't update:

<Window.Resources>
<local:Helper x:Key="helper"/>
</Window.Resources>

<TextBlock Text="{Binding Source={StaticResource helper},Path=Token Converter={StaticResource NameConverter}}"/>

我真的AP preciate任何帮助!

I really appreciate any help!

这是目前不可能,但会在.NET 4.5:另请参见WPF 4.5 - 9部分:结合静态属性

This is not currently possible, but will be in .NET 4.5: Also see "WPF 4.5 – Part 9 : binding to static properties"

有是张贴在本SO线程解决方法:问题结合静态属性

There is a workaround posted in this SO thread: Problem binding to static property