WPF 模板

一、DataTemplate(数据模板)
1、引用命名空间
xmlns:别名="clr-namespace:命名空间"

2、调用命名空间下的类别和属性
<Window.Resources>
<!--数据列表模板-->
<DataTemplate x:Key="模板名" DataType="{x:Type 别名/命名空间:类别}">
<Label Content="{Binding 属性}"></Label>
</DataTemplate>
</Window.Resources>

3、调用数据模板
<ListBox x:Name="ListBox" ItemTemplate="{StaticResource 模板名}" />

4、CS后台实例
using System;
namespace 命名空间
{
public class 类别
{
public string 属性 { get { return "我是属性"; } }
}
}

<!--在样式内创建数据列表模板-->
<Style TargetType="ListBox" x:Key="ListBox">
<Setter Property="ItemTemplate">
<Setter.Value>
<DataTemplate>
<Image Source="{Binding 属性}" Width="100" Height="100"/>
</DataTemplate>
</Setter.Value>
</Setter>
</Style>

二、ControlTemplate(控件模板)
1、控件内定义模板
<Button Grid.Row="0" Grid.Column="1" Content="控件内定义模板">
<Button.Template>
<ControlTemplate TargetType="Button">
<!--定义视觉树-->
<Label Content="{TemplateBinding Content}"></Label>
</ControlTemplate>
</Button.Template>
</Button>

2、在资源创建控件模板
<Window.Resources>
<ControlTemplate TargetType="Button" x:Key="ButtonTemplate">
<!--定义视觉树-->
<Label Content="{TemplateBinding Content}"></Label>
</ControlTemplate>
</Window.Resources>

调用:

<Button Content="控件调用模板" Template="{StaticResource ButtonTemplate}" />

3、在样式内创建控件模板
<Style x:Key="TextBox" BasedOn="{x:Null}" TargetType="{x:Type TextBox}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate>
<Border x:Name="Bd"></Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>


触发器
样式内定义触发器
<Style TargetType="Button" x:Key="TriggerButtonStyle" BasedOn="{StaticResource ButtonStyle}">
<Style.Triggers>
<Trigger Property="IsPressed" Value="True">
<Setter Property="Foreground" Value="Red"/>
</Trigger>
</Style.Triggers>
</Style>
在模板内定义触发器
<ControlTemplate TargetType="Button" x:Key="ButtonTemplate">
<!--定义视觉树-->
<Grid>
<Ellipse Name="faceEllipse" Width="{TemplateBinding Button.Width}" Height="{TemplateBinding Control.Height}" Fill="{TemplateBinding Button.Background}"/>
<TextBlock Name="txtBlock" Margin="{TemplateBinding Button.Padding}" VerticalAlignment="Center" HorizontalAlignment="Center" Text="{TemplateBinding Button.Content}" />
</Grid>
<!--定义视觉树_end-->
<!--定义触发器-->
<ControlTemplate.Triggers>
<Trigger Property="Button.IsMouseOver" Value="True">
<Setter Property="Button.Foreground" Value="Red" />
</Trigger>
</ControlTemplate.Triggers>
<!--定义触发器_End-->
</ControlTemplate>

mscorlib应用
xmlns:sys="clr-namespace:System;assembly=mscorlib"
xmlns:local="clr-namespace:项目命名空间"

<sys:String x:Key="OK">
确定
</sys:String>

<sys:ArrayList x:Key="ds">
<local:Unit Year="2011年" Price="100"/>
<local:Unit Year="2010年" Price="120"/>
<local:Unit Year="2012年" Price="140"/>
<local:Unit Year="2013年" Price="160"/>
<local:Unit Year="2014年" Price="180"/>
</sys:ArrayList>
其中Unit的代码为:
public class Unit
{
public int Price { get; set; }
public string Year { get; set; }
}

原文地址:https://www.cnblogs.com/sntetwt/p/5406597.html