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

WinUI 3:UserControl属性双向绑定失败问题求助

解决双向绑定错误:"TwoWay binding target 'Value' must be a dependency property"

问题根源

你的后台代码存在两处关键错误:

  • 依赖属性注册名称错位:CaptionProperty注册时误用了nameof(Value),ValueProperty注册时误用了nameof(Caption),导致WPF/UWP无法识别Value为合法依赖属性
  • IsEditable属性初始值类型错误:bool类型的依赖属性,初始值不应设为null,需改为布尔值

修正后的后台代码

public sealed partial class LabeledTextBox : UserControl
{
    // 正确注册Caption依赖属性
    public static readonly DependencyProperty CaptionProperty = 
        DependencyProperty.Register(nameof(Caption), typeof(string), typeof(LabeledTextBox), new PropertyMetadata(null));
    // 正确注册Value依赖属性
    public static readonly DependencyProperty ValueProperty = 
        DependencyProperty.Register(nameof(Value), typeof(string), typeof(LabeledTextBox), new PropertyMetadata(null));
    // 修正IsEditable的初始值为布尔类型
    public static readonly DependencyProperty IsEditableProperty = 
        DependencyProperty.Register(nameof(IsEditable), typeof(bool), typeof(LabeledTextBox), new PropertyMetadata(false));

    public string Caption
    {
        get => (string)GetValue(CaptionProperty);
        set => SetValue(CaptionProperty, value);
    }
    public string Value
    {
        get => (string)GetValue(ValueProperty);
        set => SetValue(ValueProperty, value);
    }
    public bool IsEditable
    {
        get => (bool)GetValue(IsEditableProperty);
        set => SetValue(IsEditableProperty, value);
    }

    public LabeledTextBox()
    {
        this.InitializeComponent();
    }
}

额外优化建议

  • 依赖属性字段必须声明为public static readonly,这是WPF/UWP的规范要求
  • 标签用的TextBox不需要双向绑定,建议将XAML中Caption的绑定模式改为OneWay:
<TextBox Text="{x:Bind Caption, Mode=OneWay}" Style="{StaticResource LabelTextBox}" Grid.Column="0"/>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 13:50:23