Jonathan
Jonathan

Reputation: 15442

Finding object in ListViewRow

I've assembled the following code in order to find an object in a ListView. I currently use this to return a TextBox on the ListViewRow that the user has selected.

private T findObjectInListView<T>(ListView lv, object item, string objectName)
    {
        ListViewItem lvi = (ListViewItem)lv.ItemContainerGenerator.ContainerFromItem(item);

        // Getting the ContentPresenter of myListBoxItem
        ContentPresenter myContentPresenter = FindVisualChild<ContentPresenter>(lvi);

        // Finding textBlock from the DataTemplate that is set on that ContentPresenter
        DataTemplate myDataTemplate = myContentPresenter.ContentTemplate;

        //Cast to chosen type and return
        return (T)myDataTemplate.FindName(objectName, myContentPresenter);
    }

This works perfectly when my ListView only contains one DataTemplate, however as soon as I add another it fails. I imagine this is because I look I'm not looking for ContentPresenter by name, and consequently the first one is just returned (which in this case does not contain the TextBox).

Can anybody point me in the right direction as to how to solve this; am I correct in thinking I need to search for a ContentPresenter by name? I can't find any articles that address this issue so I imagine I may be on the wrong track altogether...

Thank you in advance.

EDIT: This is the xaml I am using. My function works fine when I remove the first GridViewColumn:

<ListView Height="372" HorizontalAlignment="Left" Margin="12,12,0,0" Name="listView1" VerticalAlignment="Top" Width="516" MouseUp="listView1_MouseUp">
            <ListView.Resources>
                <DataTemplate x:Key="Check">
                    <StackPanel Orientation="Horizontal">
                        <CheckBox></CheckBox>
                    </StackPanel>
                </DataTemplate>
                <DataTemplate x:Key="Quantity">
                    <StackPanel Orientation="Horizontal">
                        <TextBox Text="0" Width="30" Name="quantity Foreground="LightGray" />
                    </StackPanel>
                </DataTemplate>
            </ListView.Resources>
            <ListView.View>
                <GridView>
                    <GridViewColumn Width="140" Header="Column1" CellTemplate="{StaticResource Check}" />
                    <GridViewColumn Width="140" Header="Column2" CellTemplate="{StaticResource Quantity}" />
                    <GridViewColumn Width="110" Header="Column3" DisplayMemberBinding="{Binding Name}" />
                </GridView>
            </ListView.View>
        </ListView>

Upvotes: 0

Views: 131

Answers (1)

Daniel Hilgarth
Daniel Hilgarth

Reputation: 174339

I suggest strongly, that you perform your search on the data that is bound to the ListView!

Upvotes: 3

Related Questions