原文:WPF 为资源字典 添加事件响应的后台类

前言,有许多同学在写WPF程序时在资源字典里加入了其它控件,但又想写事件来控制这个控件,但是资源字典没有CS文件,不像窗体XAML还有一个后台的CS文件,怎么办呢?

在工作时也遇到了这个问题,现在把它分享出来

比如说我们现在要写一个TabControl控件,在TabItem中有一个关闭按钮或其它按钮,这个按钮要能响应某个事件。

WPF 为资源字典 添加事件响应的后台类-LMLPHP

现在开始写资源字典里的 TabItem的样式,代码如下

  <Style x:Key="TIStyle" TargetType="{x:Type TabItem}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type TabItem}">
<Border x:Name="layout" BorderBrush="Gray" BorderThickness="1,1,1,0" Background="{TemplateBinding Background}"
CornerRadius="3" Margin="2,0,2,0">
<Grid Height="20">
<Grid.ColumnDefinitions>
<ColumnDefinition/>
<ColumnDefinition Width="25"/>
</Grid.ColumnDefinitions>
<TextBlock TextAlignment="Center" Text="{TemplateBinding Header}" Grid.Column="0" Margin="4,0,3,0"
VerticalAlignment="Center" HorizontalAlignment="Center"/>
<Button Content="X" Grid.Column="1" Height="8" Width="8" Margin="4,1,3,2"
Tag="{TemplateBinding Header}" Click="Button_Click"
Background="{x:Null}" BorderBrush="{x:Null}" VerticalAlignment="Center">
<Button.Template>
<ControlTemplate >
<Grid>
<Rectangle>
<Rectangle.Fill>
<VisualBrush>
<VisualBrush.Visual>
<Path x:Name="btnPath"
Data="M0 0L10 10M0 10L10 0" Stroke="Gray"
StrokeThickness="1"/>
</VisualBrush.Visual>
</VisualBrush>
</Rectangle.Fill>
</Rectangle>
</Grid>
<ControlTemplate.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter TargetName="btnPath" Property="Stroke" Value="Red"/>
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Button.Template>
</Button>
</Grid>
</Border>
<ControlTemplate.Triggers>
<Trigger Property="IsSelected" Value="True">
<Setter Property="Background" Value="White"/>
<Setter TargetName="layout" Property="Margin" Value="2,0,2,-1.5"/>
</Trigger>
<Trigger Property="IsSelected" Value="false">
<Setter Property="Background" Value="LightBlue"/>
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>

然后为资源字典建一个后台类DicEvent.cs

  public  partial class DicEvent : ResourceDictionary
{
public void Button_Click(object sender, RoutedEventArgs e)
{
//省去处理,如果显示,表明调用成功。
MessageBox.Show("你成功了!");
}
}

在资源字典里,添加对后台类的引用

WPF 为资源字典 添加事件响应的后台类-LMLPHP

主窗口里调用:

<Window x:Class="WpfDicButton.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">
<Grid>
<TabControl>
<TabItem Header="第一" Height=" 30" Style="{DynamicResource ResourceKey=TIStyle}"></TabItem> </TabControl>
</Grid>
</Window>

记住APP文件里加入资源字典

  <Application.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="TabControlDictionary.xaml" />
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</Application.Resources>

测试,小功告成

WPF 为资源字典 添加事件响应的后台类-LMLPHP

奉上DEMO  下载地址

04-28 12:25