【问题标题】:WPF user control dependency property not bindingWPF 用户控件依赖属性未绑定
【发布时间】:2019-03-11 20:19:39
【问题描述】:

我知道有很多类似的问题,我在过去一天左右阅读了大量的问题,但似乎没有一个解决方案对我有帮助。

我有一个 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; }
}

但是什么也没发生。当窗口加载时,客户名称不会显示在组合框中,如果我在其中输入任何内容,模型不会更新。

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

【问题讨论】:

  • 你能分享Customer类,最重要的是里面的Name属性吗?
  • @Bijington 添加了更多内容。谢谢
  • 您是否将视图模型实例分配给 Window 的 DataContext?你确定你没有没有设置 UserControl 的 DataContext 吗?
  • 另请注意,在 PropertyChangedCallback 中更新 cmb.EntityTb.Text 仅在一个方向上有效。而不是 PropertyChangedCallback,最好使用双向绑定,如 &lt;ComboBox IsEditable="True" Text="{Binding Text, RelativeSource={RelativeSource AncestorType=UserControl}, Mode=TwoWay}"/&gt;
  • @Clemens 最后一个建议让我有所收获。该值现在来自视图模型并在组合框中设置,但如果我更改组合框,该值不会发送回视图模型。有任何想法吗?我们已经成功了一半!谢谢

标签: c# wpf xaml dependency-properties


【解决方案1】:

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

取而代之的是,使用双向绑定,例如

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

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

【讨论】:

    猜你喜欢
    • 2023-03-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-11
    • 1970-01-01
    相关资源
    最近更新 更多