WPF用户控件依赖属性不绑定

问题描述 投票:2回答:1

我知道有很多类似的问题,我在过去一天左右读过它们,但没有一个解决方案似乎能帮到我。

我有一个WPF用户控件,基本上是一个加强的ComboBox,我想在其上启用数据绑定。我按照this SO question接受的答案中显示的代码,但绑定不起作用。

用户控件内容的简化版本如下......

<UserControl x:Class="Sample.MyComboBox"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <ComboBox Name="EntityTb"
              IsEditable="True" />
</UserControl>

显然还有很多,但其余的与我的问题无关。

在代码隐藏中,我添加了一个名为Text的依赖属性,如下所示......

public static readonly DependencyProperty TextProperty
         = DependencyProperty.Register("Text", typeof(string),
  typeof(MyComboBox), new FrameworkPropertyMetadata() {
    BindsTwoWayByDefault = true,
    PropertyChangedCallback = TextChanged,
    DefaultUpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged
  });


private static void TextChanged(DependencyObject d,
                             DependencyPropertyChangedEventArgs e) {
  MyComboBox cmb = (MyComboBox)d;
  cmb.EntityTb.Text = e.NewValue.ToString();
}

public string Text {
  get => (string)GetValue(TextProperty);
  set => SetValue(TextProperty, value);
}

然后我尝试在WPF窗口上使用它。视图模型有一个Customer属性,它有一个Name属性,我想绑定到自定义控件...

<controls:MyComboBox Grid.Column="1"
     Text="{Binding Customer.Name, Mode=TwoWay}" />

Customer财产并不比......更复杂。

private Customer _customer;

public Customer Customer {
  get => _customer;
  set {
    if (_customer != value) {
      _customer = value;
      RaisePropertyChanged();
    }
  }
}

...而Customer类型本身只是一个普通的C#类......

public partial class Customer {
  public string Name { get; set; }
}

但没有任何反应。当窗口加载时,客户名称不会显示在组合框中,如果我在其中键入任何内容,则不会更新模型。

我做了很多搜索,所有代码示例看起来都像上面那样。有谁能告诉我我做错了什么?

c# wpf xaml dependency-properties
1个回答
1
投票

在PropertyChangedCallback中更新cmb.EntityTb.Text只能在一个方向上工作。

而不是那样,使用双向绑定

<ComboBox IsEditable="True"
    Text="{Binding Text, RelativeSource={RelativeSource AncestorType=UserControl}}"/>

由于ComboBox.Text属性默认也绑定双向,因此设置Mode=TwoWay是多余的。

© www.soinside.com 2019 - 2024. All rights reserved.