开发者

How to bind in XAML to a static property?

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.

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(){}

And here the current XAML for the binding which work开发者_Python百科s but doesn't update:

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

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

I really appreciate any help!


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

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


In case this helps anyone else out I figured I'd post my final solution which works quite well for my purpose.

Since it turns out not to be possible without .NET 4.5 I ended up changing the property and methods to no longer be static and changed the class to a singleton then implemented INotfiyPropertyChanged and changed the XAML binding source to x:Static instead of creating an instance in Window.Resources.


Binding to static property is a problem (and unavailable in WPF) becuse of change notification (implementing INotifyPropertyChanged for static properties). Binding to static property will be introduced in WPF 4.5 (you can check it by installing .NET 4.5 Developer Preview). More details about it can be found here.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜