CoderForHire
CoderForHire

Reputation: 439

WPF MVVM User Control

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.

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

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:

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.

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

I would appreciate any help on this.

Thanks

Upvotes: 0

Views: 2638

Answers (2)

Jehof
Jehof

Reputation: 35544

CustomerList is of type ComboBox and a ComboBox has no property SelectedCustomer. The property you need for your binding is SelectedItem. You should get binding errors during your debug session in Visual Studio. See Output Window.

To get it work you need to update the binding of the CustomerId-Property to the following.

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

The TwoWay-Binding is only relevant if you want to change the Id from your AddressView. And I think that you don´t want it. So it can be removed.

Upvotes: 1

blindmeis
blindmeis

Reputation: 22445

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}" />

mainwindow

  <ComboBox X:Name=cbo .../>
  <local:AddressView DataContext="{Binding ElementName=cbo, Path=SelectedItem}"/>

customer.cs

 public Address MyAddress {get;set;}

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.

Upvotes: 2

Related Questions