Consider this data grid in wpf
<DataGrid Name="dataGrid1">
<DataGrid.Columns>
<DataGridTemplateColumn >
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<StackPanel Name= "sp" >
<TextBlock Name="textBlock1" /> </StackPanel>
<DataTemplate>
<DataGridTemplateColumn.CellTemplate>
<DataGridTemplateColumn >
<DataGrid.Columns>
</DataGrid>
To access element "textBlock1" which is inside stackpanel, we can use the following code.
foreach (StackPanel sp in FindVisualChildren<StackPanel>(dataGrid1))
{
if (sp.Name == "sp")
{
TextBlock txt= (TextBlock)sp.FindName("textBlock1");
txt.Text="Hello";
}
}
FindVisualChildren
public static IEnumerable<T> FindVisualChildren<T>(DependencyObject depObj) where T : DependencyObject
{
if (depObj != null)
{
for (int i = 0; i < VisualTreeHelper.GetChildrenCount(depObj); i++)
{
DependencyObject child = VisualTreeHelper.GetChild(depObj, i);
if (child != null && child is T)
{
yield return (T)child;
}
foreach (T childOfChild in FindVisualChildren<T>(child))
{
yield return childOfChild;
}
}
}
}
<DataGrid Name="dataGrid1">
<DataGrid.Columns>
<DataGridTemplateColumn >
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<StackPanel Name= "sp" >
<TextBlock Name="textBlock1" /> </StackPanel>
<DataTemplate>
<DataGridTemplateColumn.CellTemplate>
<DataGridTemplateColumn >
<DataGrid.Columns>
</DataGrid>
To access element "textBlock1" which is inside stackpanel, we can use the following code.
foreach (StackPanel sp in FindVisualChildren<StackPanel>(dataGrid1))
{
if (sp.Name == "sp")
{
TextBlock txt= (TextBlock)sp.FindName("textBlock1");
txt.Text="Hello";
}
}
FindVisualChildren
public static IEnumerable<T> FindVisualChildren<T>(DependencyObject depObj) where T : DependencyObject
{
if (depObj != null)
{
for (int i = 0; i < VisualTreeHelper.GetChildrenCount(depObj); i++)
{
DependencyObject child = VisualTreeHelper.GetChild(depObj, i);
if (child != null && child is T)
{
yield return (T)child;
}
foreach (T childOfChild in FindVisualChildren<T>(child))
{
yield return childOfChild;
}
}
}
}