You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

WinUI 3 如何实现静态属性的Binding或x:Bind绑定?

WinUI 3 完全支持静态属性绑定,你遇到的编译错误是因为使用了WPF专属的绑定语法,WinUI 3的XAML编译器不兼容该写法,调整为适配WinUI 3的语法即可解决。

推荐实现方案:使用x:Bind绑定

WinUI 3 优先推荐使用编译时绑定x:Bind实现静态属性绑定,有编译时校验,性能更高:

XAML代码

<TextBox Text="{x:Bind local:ViewModel.Txt, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>

静态ViewModel代码

需要调整属性变更通知的实现,WinUI 3 静态属性绑定需要使用StaticPropertyChanged事件,需先引入命名空间using System.ComponentModel;:

public static class ViewModel
{
    private static string txt;
    // 固定事件名,绑定引擎会自动识别该事件监听属性变更
    public static event PropertyChangedEventHandler StaticPropertyChanged;

    public static string Txt
    {
        get => txt;
        set
        {
            if (txt != value)
            {
                txt = value;
                StaticPropertyChanged?.Invoke(null, new PropertyChangedEventArgs(nameof(Txt)));
            }
        }
    }
}

备选实现方案:使用Binding绑定

如果必须使用Binding而非x:Bind,可以将ViewModel调整为单例模式间接绑定:

ViewModel代码

using System.ComponentModel;
using System.Runtime.CompilerServices;

public class ViewModel : INotifyPropertyChanged
{
    // 全局单例实例
    public static ViewModel Instance { get; } = new();
    // 私有构造函数禁止外部实例化
    private ViewModel() { }

    private string txt;
    public event PropertyChangedEventHandler PropertyChanged;

    public string Txt
    {
        get => txt;
        set
        {
            if (txt != value)
            {
                txt = value;
                OnPropertyChanged();
            }
        }
    }

    private void OnPropertyChanged([CallerMemberName] string propertyName = null)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
}

XAML代码

<TextBox Text="{Binding Txt, Source={x:Static local:ViewModel.Instance}, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>

内容的提问来源于stack exchange,提问作者tjb23

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.25 23:06:04