How do I get a reference to a TextBox that\'s only defined inside a DataTemplate (assuming that I\'ve just applied this DataTemplate to some cell in a grid).
So far I\'m
For getting the reference of a control inside a Data Template, handling the event and then using the sender is one of the available option. There is one more option that you can try:
private void Button_Click(object sender, RoutedEventArgs e)
{
InitializeMouseHandlersForVisual(datagrid);
}
public void InitializeMouseHandlersForVisual(Visual visual)
{
for (int i = 0; i < VisualTreeHelper.GetChildrenCount(visual); i++)
{
Visual childVisual = (Visual) VisualTreeHelper.GetChild(visual, i);
if (childVisual is TextBox)
MessageBox.Show("textbox Found");
// Recursively enumerate children of the child visual object.
InitializeMouseHandlersForVisual(childVisual);
}
}
Hope this helps!!
if you want to use x:Name then also you need to at least get the ContentPresenter and for getting ContentPresenter you need to go through the element tree. The updates you need to make are:
public void InitializeMouseHandlersForVisual(Visual visual)
{
for (int i = 0; i < VisualTreeHelper.GetChildrenCount(visual); i++)
{
Visual childVisual = (Visual) VisualTreeHelper.GetChild(visual, i);
ContentPresenter myContentPresenter = childVisual as ContentPresenter;
if (myContentPresenter != null)
{
// Finding textBlock from the DataTemplate that is set on that ContentPresenter
DataTemplate myDataTemplate = myContentPresenter.ContentTemplate;
if (myDataTemplate != null)
{
TextBox myTextBox = (TextBox)myDataTemplate.FindName("text", myContentPresenter);
MessageBox.Show("textbox Found");
}
}
InitializeMouseHandlersForVisual(childVisual);
}
}
Hope this helps!!