WPF中的模板(四)- 寻找ControlTemplate和DataTemplate的控件

一、WPF中的两棵树
WPF中每个控件的Template都是由ControlTemplate构成,ControlTemplate包含了构成该控件的各种子控件,这些子控件就构成了VisualTree;而在我们可见的界面,所有搭建出整个程序UI的控件构成了LoginTree。VisualTree和LoginTree相互独立,互相不可访问,每中树都有各自的方法来查找自己的子控件。
二、寻找ControlTemplate中的控件
首先,我们在资源中新建一个包含三个TextBox的ControlTemplate,把它赋值给一个UserControl对象;然后我们再在程序界面添加一个TextBox,在资源中引用之前把TextBox改成圆角风格的Style:

<Window x:Class="_11_221.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <Window.Resources>
        <ControlTemplate x:Key="cTmp">
            <StackPanel Background="Orange">
                <TextBox x:Name="textBox1" Margin="6"/>
                <TextBox x:Name="textBox2" Margin="6,0"/>
                <TextBox x:Name="textBox3" Margin="6"/>
            </StackPanel>
        </ControlTemplate>
        <Style BasedOn="{x:Null}" TargetType="{x:Type TextBox}" x:Key="tbstyle">
            <Setter Property="Foreground" Value="{DynamicResource {x:Static SystemColors.ControlTextBrushKey}}"/>
            <Setter Property="Background" Value="{DynamicResource {x:Static SystemColors.WindowBrushKey}}"/>
            <Setter Property="BorderThickness" Value="1"/>
            <Setter Property="Padding" Value="1"/>
            <Setter Property="AllowDrop" Value="true"/>
            <Setter Property="FocusVisualStyle" Value="{x:Null}"/>
            <Setter Property="ScrollViewer.PanningMode" Value="VerticalFirst"/>
            <Setter Property="Stylus.IsFlicksEnabled" Value="False"/>
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="{x:Type TextBox}">
                        <Border x:Name="Bd" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Background="{TemplateBinding Background}"  SnapsToDevicePixels="true"
                        CornerRadius="10">
                            <TextBlock x:Name="textblck1" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}"/>
                        </Border>
                        <ControlTemplate.Triggers>
                            <Trigger Property="IsEnabled" Value="false">
                                <Setter Property="Background" TargetName="Bd" Value="{DynamicResource {x:Static SystemColors.ControlBrushKey}}"/>
                                <Setter Property="Foreground" Value="{DynamicResource {x:Static SystemColors.GrayTextBrushKey}}"/>
                            </Trigger>
                        </ControlTemplate.Triggers>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>

    </Window.Resources>
    <Grid>
        <StackPanel Background="Yellow">
            <UserControl x:Name="uc" Template="{StaticResource cTmp}" Margin="5"/>
            <TextBox x:Name="tb"  Style="{StaticResource tbstyle}"/>
            <Button Content="find" Width="120" Height="30" Click="Button_Click"/>
        </StackPanel>    
    </Grid>
</Window>

我们实现的效果是,点击按钮,分别从UserControl和TextBox中找到构成他们的ControlTemplate,然后找到子控件并进行相关操作:
后台代码:

private void Button_Click(object sender, RoutedEventArgs e)
        {
            TextBox t = this.uc.Template.FindName("textBox1", this.uc) as TextBox;
            t.Text = "hello";
            StackPanel sp = t.Parent as StackPanel;
            (sp.Children[1] as TextBox).Text = "hello controltemplate";
            (sp.Children[2] as TextBox).Text = "find it";

            TextBlock tbl = this.tb.Template.FindName("textblck1", this.tb) as TextBlock;
            tbl.Text = "in textbox";
        }

这里写图片描述
ControlTemplate和DateTemplate都属于Template,都可以给Template进行赋值,Template中提供了一个叫做FindName的接口,可以用来寻找模板中的控件。

三、寻找DataTemplate中的控件
首先,先定义一个用于使用DataTemplate的类Student:

public class Student
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string Skill { get; set; }
        public bool HasJob { get; set; }
    }

XMAL代码如下:

<Window x:Class="_11_222.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:_11_222"
        Title="MainWindow" Height="350" Width="525">
    <Window.Resources>
        <local:Student x:Key="stu" Id="1"  Name="Hyman" Skill="Linux" HasJob="True"/>
        <DataTemplate x:Key="stuDT">
            <StackPanel Orientation="Horizontal">
                <TextBox  Name="textbox1" Text="{Binding Id}"/>
                <TextBox  Name="textbox2" Text="{Binding Name}"/>
                <TextBox  Name="textbox3" Text="{Binding Skill}"/>
            </StackPanel>
        </DataTemplate>
    </Window.Resources>
    <Grid>
        <StackPanel>
            <ContentPresenter x:Name="cp" Content="{StaticResource stu}" ContentTemplate="{StaticResource stuDT}" />
            <Button x:Name="button" Width="120" Height="30"  Click="button_Click" Content="find"/>
        </StackPanel>
    </Grid>
</Window>

实现find按钮的处理函数,将找到的TextBox中的内容用MessageBox弹出:

private void button_Click(object sender, RoutedEventArgs e)
        {
            TextBox tb = this.cp.ContentTemplate.FindName("textbox2", this.cp) as TextBox;
            MessageBox.Show(tb.Text);
        }

界面效果如下:
这里写图片描述
这里写图片描述

  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,首先我们需要安装MVVM Light框架,可以通过NuGet包管理器进行安装。 接下来,我们可以创建一个新的WPF项目,然后在项目添加MVVM Light的参考。 在项目添加自定义控件,可以通过继承现有的控件或者创建全新的控件。这里我们以创建一个自定义Button为例。 在项目创建一个新的文件夹,命名为“Controls”,然后在该文件夹下创建一个新的类,命名为“CustomButton”。 在该类,我们需要继承现有的Button控件,并且重写其默认样式。代码如下: ```csharp public class CustomButton : Button { static CustomButton() { DefaultStyleKeyProperty.OverrideMetadata(typeof(CustomButton), new FrameworkPropertyMetadata(typeof(CustomButton))); } public CustomButton() { this.Background = Brushes.Green; this.Foreground = Brushes.White; } } ``` 在XAML,我们需要定义CustomButton的默认样式。代码如下: ```xaml <Style TargetType="{x:Type local:CustomButton}"> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="{x:Type local:CustomButton}"> <Border Background="{TemplateBinding Background}" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}"> <ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center"/> </Border> </ControlTemplate> </Setter.Value> </Setter> </Style> ``` 最后,在视图模型使用自定义控件,代码如下: ```csharp public class MainViewModel : ViewModelBase { public CustomButton MyButton { get; set; } public MainViewModel() { MyButton = new CustomButton(); MyButton.Content = "Click me!"; } } ``` 在视图,我们可以使用DataTemplate来绑定自定义控件。代码如下: ```xaml <Window.Resources> <DataTemplate DataType="{x:Type local:CustomButton}"> <ContentPresenter Content="{Binding}" /> </DataTemplate> </Window.Resources> <Grid> <local:CustomButton Content="{Binding MyButton}" /> </Grid> ``` 这里我们使用了DataTemplate来绑定自定义控件,这样我们就可以在视图使用自定义控件了。 以上就是使用MVVM Light框架搭建WPF应用程序并使用自定义控件的基本步骤。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值