访问Template 内部控件

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";
        }

  

2.访问 DataTemplate 内部的控件

需要注意的是,如果我们想获取模板内部某个控件的值,这样做就没有必要了,因为 DataTemplate 内容 是绑定好的,我们可以很容易获取

如果想要获取 控件的属性 ,如果height,width 等等属性

 

 

<Window.Resources>
        <local:Employee x:Key="stu" name="張三" age="20"></local:Employee>
        <DataTemplate x:Key="dt">
            <StackPanel Orientation="Vertical">
                <StackPanel Orientation="Horizontal">
                    <TextBlock Text="Name:" ></TextBlock>
                    <TextBlock Text="{Binding name}" x:Name="t1"></TextBlock>
                </StackPanel>
                <StackPanel Orientation="Horizontal">
                    <TextBlock Text="age:"></TextBlock>
                    <TextBlock Text="{Binding age}"></TextBlock>
                </StackPanel>
            </StackPanel>
        </DataTemplate>
    </Window.Resources>
    <StackPanel>
        <ContentPresenter x:Name="uc" ContentTemplate="{StaticResource dt}" Content="{StaticResource stu}" Height="36"></ContentPresenter>
        <Button Click="Button_Click" Height="34" Content="顯示指定TextBolck的name屬性"></Button>
    </StackPanel>

  

var t=this.uc.ContentTemplate.FindName("t1",uc) as TextBlock;
            MessageBox.Show(t.Text); // 获取控件内部的值

            //var stu = this.uc.Content as Employee;  // 获取 DataTemplate 绑定的 内容
            //MessageBox.Show(stu.name+"   "+stu.age);

  

 

posted @ 2021-08-30 19:56  zq爱生活爱代码  阅读(68)  评论(0编辑  收藏  举报