我正在使用MVVM开发WPF应用程序。在主窗口上是一个客户名称的组合框。选择客户后,我想显示它的地址。
所以我创建了一个Address用户控件,在后面的控件代码中我添加了一个DP:
public static DependencyProperty CustomerIdProperty =
DependencyProperty.Register("CustomerId", typeof(int), typeof(AddressView));
public int CustomerId
{
get { return (int)GetValue(CustomerIdProperty); }
set { SetValue(CustomerIdProperty, value); }
}
接下来,在主窗口中,我将组合绑定到用户控件的CustomerId DP:
<vw:AddressView Grid.Row="1"
Grid.Column="0"
x:Name="AddressList"
CustomerId="{Binding ElementName=CustomersList, Path=SelectedCustomer.Id, Mode=TwoWay}"/>
我现在有一个问题和一个问题:
问题:当我运行此选择客户时,DP上的设置器永远不会触发。将触发主窗口中的SelectedCustomer属性,但不会触发用户控件中的DP。
问题:控件的ViewModel如何了解DP中的CustomerId?
我在这里创建了一个小样本应用程序来演示我正在做的事情:
我将不胜感激。
由于
答案 0 :(得分:2)
而不是使用依赖项属性,当客户对象也具有地址属性
时,您可以轻松实现 <AdressView>
<TextBlock Text="{Binding Path=MyAddress.Name}" />
<TextBlock Text="{Binding Path=MyAddress.Street}" />
主窗口
<ComboBox X:Name=cbo .../>
<local:AddressView DataContext="{Binding ElementName=cbo, Path=SelectedItem}"/>
customer.cs
public Address MyAddress {get;set;}
如果你想让你的依赖属性工作,你必须发布你的地址视图的代码,以便我们可以检查绑定到依赖属性,你必须提供一些信息,你想如何获得与customerid的地址
答案 1 :(得分:1)
CustomerList
的类型为ComboBox
,而ComboBox没有属性SelectedCustomer。绑定所需的属性是SelectedItem
。 您应该在Visual Studio中的调试会话期间遇到绑定错误。请参阅输出窗口。
要使其正常工作,您需要将CustomerId-Property的绑定更新为以下内容。
CustomerId="{Binding ElementName=CustomersList, Path=SelectedItem.Id}"
只有当您想要更改Id
中的AddressView
时,才能使用TwoWay-Binding。而且我认为你不想要它。所以它可以删除。