I have quite a simple question regarding WPF. I’ve searched around but didn’t find the “the Answer” yet…
I would like to do a 2-level Data Binding. Simplified, I have a Person with some attributes, that also has N Addresses, each of some type and with some Zip Code (both selectable from a combo).
I retrieve the following Data from the server:
public List<AddressType> AddressTypeList; // catalogue of Address Types
public List<ZipCode> ZipCodeList; // catalogue of Zip Codes
public Person Person; // Person object
public List<Address> PersonAddressList; // Address List for that person (each has AddresType and ZipCode property)
Now, I’d like to bind this data to some controls. So, I put these properties into some custom class (say Data) and set the main user control’s DataContext property to this object:
data = new Data();
data.AddressTypeList = dao.GetAll<AddressType>();
data.ZipCodeList = dao.GetAll<ZipCode>();
data.Person = dao.GetPerson();
data.PersonAddressList = dao.GetPersonAddressList(Person);
this.DataContext = data; // this == some parent UserControl
Now, my XAML part for Address List looks something like this:
<ListBox Name="listBoxAddressList" ItemsSource="{Binding PersonAddressList}">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<ComboBox ItemsSource="{Binding AddressTypeList}" SelectedItem="{Binding AddressType}"/>
<TextBox Text="{Binding Address}"/> <!-- this works! -->
<ComboBox ItemsSource="{Binding ZipCodeList}" SelectedItem="{Binding ZipCode}"/>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
The Address property gets bound OK, but the AddressTypeList and ZipCodeList don’t. It’s kind of logical, since the PersonAddress (in PersonAddressList) doesn’t have that property (they are on a different level!). I don’t want to put the whole list of AddressTypes and ZipCodes into each address object, I would like to most painlessly bind it to “parent” or pass it to each Address List Item object somehow in XAML.
I think it’s a common request to have a catalogue of some values in a combo (one list), but one of them is selected and that value is bound to another object’s property. How would that be done properly?
Edit 2: You could also try to set up your lists as static properties, that way you might be able to bind directly using something like:
Edit: Try using RelativeSource to get back to the original data, something like this:
Also: Bind
SelectedValueto the property instead ofSelectedItem.e.g.