WPF TwoWay Binding to a static class Property

前端 未结 3 2129
遥遥无期
遥遥无期 2020-12-01 20:25

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

namespace Halt
{
    public class ProjectData
    {
            public static string Username {ge         


        
相关标签:
3条回答
  • 2020-12-01 20:38

    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.

    0 讨论(0)
  • 2020-12-01 20:38

    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.

    0 讨论(0)
  • 2020-12-01 20:47

    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}"/>
    
    0 讨论(0)
提交回复
热议问题