首页 文章

WPF MVVM用户控件

提问于
浏览
0

我正在使用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?

我在这里创建了一个小样本应用程序来演示我正在做的事情:

http://sdrv.ms/17OZv1x

我将不胜感激任何帮助 .

谢谢

2 回答

  • 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

    CustomerList 的类型为 ComboBox ,而ComboBox没有属性SelectedCustomer . 绑定所需的属性是 SelectedItem . 您应该在Visual Studio中的调试会话期间遇到绑定错误 . 请参见输出窗口 .

    要使其工作,您需要将CustomerId-Property的绑定更新为以下内容 .

    CustomerId="{Binding ElementName=CustomersList, Path=SelectedItem.Id}"
    

    仅当您想要从 AddressView 更改 Id 时,TwoWay-Binding才有意义 . 而且我认为你不想要它 . 所以它可以删除 .

相关问题