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
相关产品推荐
相关产品推荐

