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

查看:53
本文介绍了WPF 双向绑定到静态类属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果 Mode=OneWay 没有问题,但我有这个:班级:

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

这不会因为 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天全站免登陆