WPF TwoWay Binding to a static class Property

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.


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

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.