Wednesday, April 6, 2011

Wpf binding with nested properties

ViewModel

I have a property of type Member called KeyMember. The 'Member' type has an ObservableCollection called Addresses. The Address is composed of two strings - street and postcode .

View

I have a ListBox whose item source need to be set to ViewModels's KeyMember property and it should display the Street of all the Past Addresses in the Address collection.

Question

My ViewModel and View relationship is established properly.

I am able to write a data template for the above simple case as below

<ListBox ItemsSource="{Binding KeyMember.Addresses}">
    <ListBox.ItemTemplate>
        <DataTemplate DataType="Address">
            <TextBlock Text="{Binding Street}"/>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

I am curios to know how to write the DataTemplate if I change KeyMember from type Member to ObservableCollection< Member > assuming that the collection has only one element. I am not sure whether this is a valid scenrio and it's implementation feasibility.

PS: I know that for multiple elements in collection, I will have to implement the Master-Detail pattern/scenario. I am looking into this at the moment.

From stackoverflow
  • If you want to bind to the 0th element, you can do {Binding Path=[0].Addresses}, and likewise for any other elements in a collection that supports array-style indexing. I agree with Wonko though that this is a rather unusual requirement.

    byte : JustABill, Thank you for the reply. As I mentioned earlier this is not a requirement for my work. This question is more on lines of curiosity. Being a novice, bindings like {Binding Path=[0].Addresses} is something new that I didn't know and is exactly what I wanted to know - whether explicityly binding to a particular element in collection is possible or not. Ofcourse I would not be using this in my work as I will not explicitly bind to a particular element from collection. But it's always good to know what is possible even when, in practice, it might not be the best thing to do.
    JustABill : Ah, curiosity is fine. You'll see the [0] in Binding Paths commonly when you get to validation - it's a common (but poor) way to retrieve the current error message. Both in that specific case and possibly in yours, if the collection is ever null you should not do this because trying to get the [0] element from a null collection will make WPF throw an exception, which you won't see but which will slow down your program.
    byte : Thanks. Is there any online resource where I can read advance data binding techniques?
    JustABill : I'm not aware of anything specific to recommend, but most of the fun stuff I've seen involves the RelativeSource parameter. So you can (to use a stupid example) make a UserControl the same background color as that of its parent Window. So maybe look at that.

0 comments:

Post a Comment