WPF双向绑定到一个静态类属性
问题描述:
还有,如果模式=单向没有问题,但我有这样的: 类别:
There's no problem if Mode=OneWay, but I have this: Class:
namespace Halt
{
public class ProjectData
{
public static string Username {get;set;}
}
}
和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?
答
如果绑定需要是双向的,你必须提供一个路径。还有一招,做双向的静态属性绑定,提供的类不是静态的:声明类的资源,一个虚拟实例,并把它作为绑定的源
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}"/>