1

I have a ListView that displays a few TextBoxes. For each TextBox, I am catching a SelectionChanged event.

My XAML file looks something like this:

<ListView>
    <GridView>
        ...
        <DataTemplate>
            <TextBox SelectionChanged="Box_SelectionChanged" />
        </DataTemplate>
        ...
    </GridView>
</ListView>

And my Xaml CS file looks like this:

private void Box_SelectionChanged(object sender, TextChangedEventArgs e) {}

In my Box_SelectionChanged function, I would like to get the ListViewItem in which the text box was updated.

How can I do so?

4
  • @Bob. - I have tried casting the sender as a TextBox to see if I can get the ListViewItem from that but had no luck Commented Sep 26, 2012 at 19:22
  • When you debug, what kind of object does sender show up as? Commented Sep 26, 2012 at 19:23
  • @Bob. It's of type System.Windows.Controls.TextBox Commented Sep 26, 2012 at 19:29
  • Odd, that walking up the visual tree in the debugger, you couldn't find the ListView Commented Sep 26, 2012 at 19:40

1 Answer 1

5

You can try this:

Add this method to your class:

public static T FindVisualParent<T>(UIElement element) where T : UIElement
        {
            UIElement parent = element; while (parent != null)
            {
                T correctlyTyped = parent as T; if (correctlyTyped != null)
                {
                    return correctlyTyped;
                }
                parent = VisualTreeHelper.GetParent(parent) as UIElement;
            } return null;
        }

And in Box_SelectionChanged event handler invoke this method:

        private void Box_SelectionChanged(object sender, RoutedEventArgs e)
        {          
            var tmp = FindVisualParent<ListViewItem>(sender as TextBox);
        }
Sign up to request clarification or add additional context in comments.

2 Comments

Cool, thanks. Is there a way of getting the parent through a property or method in the sender object or do I have to perform a search on the entire ListView every time?
You're welcome. You don't perform search on entire ListView, everytime when you invoke this method you're checking only 7 elements. You can check this in Snoop (snoopwpf.codeplex.com).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.