WPF MVVM 用户控件 [英] WPF MVVM User Control

查看:49
本文介绍了WPF MVVM 用户控件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 MVVM 开发 WPF 应用程序.在主窗口上是一个客户名称组合框.选择客户后,我想显示其地址.

I am working on a WPF app using MVVM. On the main windows is a combo box of customer names. When a customer is selected I want to show the addresses for it.

所以我创建了一个 Address 用户控件,并在控件后面的代码中添加了一个 DP:

So I created an Address user control and in the control's code behind I added a 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:

Next, in the main window I bound the combo to the user control's CustomerId DP:

<vw:AddressView Grid.Row="1"
                Grid.Column="0"
                x:Name="AddressList"
                CustomerId="{Binding ElementName=CustomersList, Path=SelectedCustomer.Id, Mode=TwoWay}"/>

我现在有一个问题和一个问题:

I now have a problem and a question:

问题:当我运行它并选择一个客户时,DP 上的 setter 永远不会触发.主窗口中的 SelectedCustomer 属性会触发,但用户控件中的 DP 属性不会触发.

Problem: When I run this and select a customer, the setter on the DP never fires. The SelectedCustomer property in the Main Window fires, but not the DP in the user control.

问题:控件的 ViewModel 如何知道 DP 中的 CustomerId?

Question: How does the ViewModel for the control know about the CustomerId in the DP?

我在这里创建了一个小示例应用程序来演示我在做什么:

I have created a small sample app here to demonstrate what I'm doing:

http://sdrv.ms/17OZv1x

我将不胜感激.

谢谢

推荐答案

当您的客户对象也具有地址属性时,您可以使用一种简单的方法,而不是使用依赖属性

instead of using dependency properties you can go an easy way when your customer object also has the address property

 <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

customer.cs

 public Address MyAddress {get;set;}

如果你想让你的依赖属性工作,你必须发布你的地址视图的代码,这样我们就可以检查依赖属性的绑定,你必须提供一些信息,你想如何使用你的客户 ID 获取地址.

if you want your dependency property stuff to work, you have to post the code for your addressview, so that we can check the bindings to the dependency properties and you have to give some information how you wanna get the address with your customerid.

这篇关于WPF MVVM 用户控件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆