WPF TwoWay Binding to a static class Property

耗尽温柔 提交于 2019-12-28 06:25:14

问题


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?


回答1:


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}"/>



回答2:


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.




回答3:


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.



来源:https://stackoverflow.com/questions/31609312/wpf-twoway-binding-to-a-static-class-property

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!