訪問Template 內部控制元件 ListBox 詳細例項
阿新 • • 發佈:2021-08-30
ControlTemplate 和 DataTemplate 都是派生自FrameworkTemplate, 這個類有 FindName 方法 訪問內部的控制元件
也就是說只有我們獲得了Template 就可以訪問內部控制元件。
對於ControlTemplate,訪問控制元件的Template屬性即可。但是對於 DataTemplate 則要麻煩一些
1、訪問 ControlTemplate 內部控制元件
<Window.Resources> <ControlTemplate x:Key="ctemp"> <StackPanel Background="Orange"> <TextBlock x:Name="t1" Margin="6" Background="White"></TextBlock> <TextBlock x:Name="t2" Margin="6,6" Background="White"></TextBlock> <TextBlock x:Name="t3" Margin="6" Background="White"></TextBlock> </StackPanel> </ControlTemplate> </Window.Resources> <StackPanel Background="Yellow"> <UserControl x:Name="uc" Template="{StaticResource ctemp}" Margin="5"></UserControl> <Button Content="Find by Name" Click="Button_Click"></Button> </StackPanel>
private void Button_Click(object sender, RoutedEventArgs e) { TextBlock tb = this.uc.Template.FindName("t1", this.uc) as TextBlock; tb.Text = "Hello Wpf"; StackPanel sp=tb.Parent as StackPanel; var tb2=sp.Children[1] as TextBlock; var tb3=sp.Children[2] as TextBlock; tb2.Text="Control Template"; tb3.Text= "I Can Find you"; }