Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF TwoWay Binding to a static class Property

There's no problem if Mode=OneWay, but I have this: Class:

namespace Halt
{
    public class ProjectData
    {
            public static string Username {get;set;}
    }
}

And XAML:

xmlns:engine="clr-namespace:Halt.Engine"
<TextBox Name="UsernameTextBox" HorizontalAlignment="Stretch" Margin="10,5,10,0" Height="25"
         Text="{Binding Source={x:Static engine:ProjectData.Username}, Mode=TwoWay}"/>

This dont wanna work because of TwoWay mode. So how to fix it?

like image 894
Iworb Avatar asked Jul 24 '15 11:07

Iworb


3 Answers

Use the static property binding syntax (which is, as far as I know, available since WPF 4.5):

<TextBox Text="{Binding Path=(engine:ProjectData.Username)}"/>

No need to set Mode="TwoWay", as that is the default for the TextBox.Text property anyway.


Although not explicitly asked for, you may also want to implement property change notification.

See this answer for how to do it.

like image 193
Clemens Avatar answered Sep 30 '22 04:09

Clemens


If the binding needs to be two-way, you must supply a path. There's a trick to do two-way binding on a static property, provided the class is not static : declare a dummy instance of the class in the resources, and use it as the source of the binding.

<Window.Resources>
    <local:ProjectData x:Key="projectData"/>
</Window.Resources>
...

<TextBox Name="UsernameTextBox" HorizontalAlignment="Stretch" Margin="10,5,10,0" Height="25"
         Text="{Binding Source={StaticResource projectData}, Path=Username}"/>
like image 43
Carbine Avatar answered Sep 30 '22 06:09

Carbine


When I have to bind to a static property I use a ViewModel that has a property that gets and sets on the static property, for example

public class ProjectData
{
        public static string Username {get;set;}
}

public class ViewModel {
   public string UserName {
      get{ return ProjectData.Username ; }
      set { ProjectData.Username  = value; }
   }
}

Then I set an instance of ViewModel as the UI DataContext.

like image 38
Murilo Avatar answered Sep 30 '22 04:09

Murilo