我在DataTemplate中有一个自定义控件`AutoCompleteTextBox,如下所示:
<DataGridTextColumn.HeaderTemplate>
<DataTemplate>
<StackPanel Orientation="Vertical">
<TextBlock
Text="{Binding Content, RelativeSource={RelativeSource Mode=TemplatedParent}}"
Margin="5" />
<Border DockPanel.Dock="Top"
HorizontalAlignment="Left"
VerticalAlignment="Center"
Padding="2">
<uc:AutoCompleteTextBox x:Name="AutoTextBox" />
</Border>
</StackPanel>
</DataTemplate>
</DataGridTextColumn.HeaderTemplate>
如何在代码背后访问AutoTextBox
?
答案 0 :(得分:0)
无法直接按名称访问DataTemplate中的控件!但你可以尝试下载VisualTree ......
DependencyObject dgColumnHeader = GetYourColumnHeader();
var yourAutoCompleteTextBox = FindVisualChild<AutoCompleteTextBox>(dgColumnHeader);
public static T FindVisualChild<T>(DependencyObject parent) where T : DependencyObject
{
for (int i = 0; i < VisualTreeHelper.GetChildrenCount(parent); i++)
{
DependencyObject child = VisualTreeHelper.GetChild(parent, i);
if (child != null && child is T)
return (T)child;
else
{
T childOfChild = FindVisualChild<T>(child);
if (childOfChild != null)
return childOfChild;
}
}
return null;
}