[英]WPF TwoWay Binding to a static class Property
There's no problem if Mode=OneWay, but I have this: Class: 如果Mode = OneWay没有问题,但我有:Class:
namespace Halt
{
public class ProjectData
{
public static string Username {get;set;}
}
}
And XAML: 和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. 由于TwoWay模式,这不想工作。 So how to fix it? 那么如何解决呢?
Use the static property binding syntax (which is, as far as I know, available since WPF 4.5): 使用静态属性绑定语法(据我所知,自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. 无需设置Mode="TwoWay"
,因为这是TextBox.Text
属性的默认值。
Although not explicitly asked for, you may also want to implement property change notification. 虽然没有明确要求,但您可能还希望实现属性更改通知。
See this answer for how to do it. 请参阅此答案以了解如何操作。
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 当我必须绑定到静态属性时,我使用ViewModel,该ViewModel具有在静态属性上获取和设置的属性,例如
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. 然后我将ViewModel的实例设置为UI DataContext。
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}"/>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.