我知道有很多类似的问题,我在过去一天左右阅读了很多,但似乎没有一个解决方案对我有帮助。
我有一个 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/