WPF双向绑定到一个静态类属性 [英] WPF TwoWay Binding to a static class Property

查看:1183
本文介绍了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}"/>

这篇关于WPF双向绑定到一个静态类属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆