c# - WPF 用户控件依赖属性未绑定(bind)

标签 c# wpf xaml dependency-properties

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

我有一个 WPF 用户控件,它基本上是一个增强型 ComboBox,我想在其上启用数据绑定(bind)。我遵循了 this SO question 的已接受答案中显示的代码,但绑定(bind)不起作用。

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

<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 窗口中使用它。 View 模型有一个 Customer 属性,它有一个 Name 属性,我想将其绑定(bind)到自定义控件...

<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; }
}

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

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

最佳答案

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

取而代之的是,使用像这样的双向绑定(bind)

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

由于 ComboBox.Text 属性在默认情况下也绑定(bind)双向,因此设置 Mode=TwoWay 是多余的。

关于c# - WPF 用户控件依赖属性未绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55109761/

相关文章:

.net - WPF GUI 负责什么?

c# - 如何在运行时决定使用 PLINQ 还是 LINQ?

c# - Xamarin - 显示来自 base64 字符串的图像

c# - 如何将源类型 'System.Nullable<bool>' 转换为目标类型 'bool'

c# - 如何使用 ScaleTransform 缩放到任意中心点?

c# - 带有 WPF 的 SlimDX RawInput

c# - WPF 中 DataGrid 中的条件 CanUserAddRows

c# - 在没有打开 Outlook 应用程序的情况下阅读电子邮件

C# UDP 现有连接被远程主机强行关闭

c# - 使用 IDisposable 时卸载 AppDomain