Tired of writing these two methods over and over, from now on just going to Copy/Paste them from here :)
1:
2: static T FindVisualParent<T>(UIElement element) where T : UIElement
3: {
4: var parent = element;
5: while (parent != null)
6: {
7: T correctlyTyped = parent as T;
8:
9: if (correctlyTyped != null)
10: return correctlyTyped;
11:
12: parent = VisualTreeHelper.GetParent(parent) as UIElement;
13: }
14: return null;
15: }
16:
17: static T FindVisualChild<T>(Visual parent) where T : Visual
18: {
19: T child = default(T);
20: int numVisuals = VisualTreeHelper.GetChildrenCount(parent);
21: for (int i = 0; i < numVisuals; i++)
22: {
23: var visual = (Visual)VisualTreeHelper.GetChild(parent, i);
24:
25: child = visual as T;
26: if (child == null)
27: child = FindVisualChild<T>(visual);
28:
29: if (child != null)
30: break;
31:
32: }
33: return child;
34: }
35: }
36:
37: //call samples:
38: var dataGrid = FindVisualParent<DataGrid>(cell);
39: var row = FindVisualParent<DataGridRow>(cell);
40: var textBox = FindVisualChild<TextBox>(e.EditingElement);