WPF TwoWay Static Class Binding Property

No problem if Mode = OneWay, but I have: 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 does not need to work due to TwoWay mode. So how to fix this?

+5
source share
3 answers

If the binding should be two-way, you must specify the path. There is a trick for two-way binding to a static property, if the class is not static: declare a dummy instance of the class in resources and use it as a binding source.

 <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}"/> 
+2
source

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

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

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


Although this is not explicitly specified, you can also notify you of a property change.

For more on how to do this, see this answer .

+9
source

When I need to bind to a static property, I use a ViewModel that has a property that gets and sets a static property, like

 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 install the ViewModel instance as a UI DataContext.

+2
source

All Articles