我想在TabItem中找到一个控件。使用FindName是不可能的。我找到了一种遍历可视化树的方法,但看起来相当麻烦。为什么FindName不能完成这项工作?
XAM:
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<Button
Content="Click"
Click="Button_Click"
/>
<TabControl Grid.Row="1" x:Name="tabControl">
<TabControl.ContentTemplate>
<DataTemplate>
<StackPanel>
<TextBox
x:Name="textBox"
Text="{Binding DataContext.Message, ElementName=mainWindow}"
/>
</StackPanel>
</DataTemplate>
</TabControl.ContentTemplate>
<TabItem Header="One" />
<TabItem Header="Two" />
<TabItem Header="Three" />
</TabControl>
</Grid>
后面的代码:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
TabControl tabControl = FindName("tabControl") as TabControl;
TextBox textBox = FindName("textBox") as TextBox;
TabItem tabItem = tabControl.SelectedItem as TabItem;
textBox = tabItem.FindName("textBox") as TextBox;
}
}
"textBox "是空的,不管是从顶部还是从选定的tabItem搜索。
XAM: The TextBox
不是视觉上的孩子 TabItem
. 如果你看一下可视化树,你会看到当前选择的标签页的内容被托管在一个叫 ContentPresenter
属于 TabControl
's ControlTemplate
.
但这应该是工作。
private void Button_Click(object sender, RoutedEventArgs e)
{
ContentPresenter cp = tabControl.Template.FindName("PART_SelectedContentHost", tabControl) as ContentPresenter;
TextBox textBox = cp.ContentTemplate.FindName("textBox", cp) as TextBox;
}