patryk.beza
patryk.beza

Reputation: 5136

One way binding to static property fails

I have problem with binding to static property.
I want to have Label with Content true or false depending on the value of bool variable.

XAML:

<Label Content="{Binding Source={x:Static l:MainWindow.IsTrue}, Mode=OneWay}" />

Code behind:

public partial class MainWindow : Window
{
    public static bool IsTrue { get; set; }
    DispatcherTimer myTimer;

    public MainWindow()
    {
        InitializeComponent();

        myTimer = new DispatcherTimer();
        myTimer.Interval = new TimeSpan(0, 0, 2); // tick every 2 seconds
        myTimer.Tick += new EventHandler(myTimer_Tick);
        myTimer.IsEnabled = true;
    }

    void myTimer_Tick(object sender, EventArgs e)
    {
        IsTrue = !IsTrue;
    }
}

It displays False all the time.

I know that in order to implement two way binding I need to specify Path. But I need one way binding.

Upvotes: 2

Views: 784

Answers (1)

Reed Copsey
Reed Copsey

Reputation: 564323

The problem is that WPF doesn't know when (or if) your property changes. Unlike an instance method, there is no INotifyPropertyChanged-style interface you can implement, since you can't have a "static interface." As such, it never sees your changed value.

If you're using WPF 4.5, you can use the new static property changed notification support to handle this.

In .NET 4.0 or earlier, the easiest way to handle this is typically to wrap the property into a singleton, and use INotifyPropertyChanged on the singleton instance.

Upvotes: 7

Related Questions