tags:

views:

488

answers:

2

Given a populated ListView how do I iterate through each bound 'template' and pluck out the contained ComboBox (or any other control contained in 'DataTemplate')?

<ListView x:Name="lstCommands">
<ListView.ItemTemplate>
    <DataTemplate>
        <Grid x:Name="gridInputs">
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="100"/>
                <ColumnDefinition Width="*"/>
            </Grid.ColumnDefinitions>
            <Label Content="{Binding Path=Key}"/>
            <ComboBox x:Name="cbInputCmd" Grid.Column="1" ItemsSource="{Binding Source={StaticResource inputData}}" Tag="{Binding Path=Key}"/>
        </Grid>
    </DataTemplate>
</ListView.ItemTemplate>

+1  A: 

Firstly, avoid doing so unless you really need to. If you absolutely must, you can use DataTemplate.FindName, where the templated parent is the ListViewItem generated by the ListView. To get the ListViewItem, use the ListView's ItemContainerGenerator.

HTH,
Kent

Kent Boogaart
A: 

you could try using the LogicalTreeHelper or VIsualTreeHelper which lets you query an object for its children, but if you were binding your combo boxes to the item your list view is displaying you would not have to worry about 'getting' them at all.

then you could just look at your item.

any time you find yourself walking the visual or logical tree looking for elements which exist in your ui, so that you can get their values, ask yourself 'what am i missing here' 'why isnt my business (or view model) being updated with relevant data when the user interacts with the ui?'

for the above example i would build a view model that had two properties, a String (for your label) and a SelectedItem (that you could bind your combo box selected item to). its easier, more robust and it stops you having to trawl through the visual elements. one of the beautiful things about xaml/wpf is that it seperates your logic from your view. what you are suggesting will break this model. you will entangle the view with your logic and from there on it gets messy....

Aran Mulholland