有时候需要动态的设置一些按钮的状态模板。使一个button显示不同的内容,比如Button未点击安装显示:
安装后显示:
可以通过设置button的content,通过content来设置不同的模板来实现功能,以下是代码:
MainWindow.xaml
<Window
x:Class="WPF_ButtonTemplate.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:WPF_ButtonTemplate"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
Title="MainWindow"
Width="800"
Height="450"
mc:Ignorable="d">
<Window.Resources>
<BitmapImage x:Key="Setting_Extension" UriSource="pack://application:,,,/Installed.png" />
<ControlTemplate x:Key="UnInstallTemplate" TargetType="Button">
<Border
x:Name="border1"
Width="100"
Height="30"
Background="LightGray"
BorderBrush="DarkGray"
BorderThickness="1.5"
CornerRadius="8">
<TextBlock
x:Name="contentTB"
HorizontalAlignment="Center"
VerticalAlignment="Center"
Text="{TemplateBinding Content}" />
</Border>
</ControlTemplate>
<ControlTemplate x:Key="InstalledTemplate" TargetType="Button">
<Border x:Name="border1" Background="LightYellow" CornerRadius="8">
<StackPanel Margin="13,7,13,7" Orientation="Horizontal">
<Image
Width="16"
Height="16"
HorizontalAlignment="Left"
VerticalAlignment="Center"
Source="{DynamicResource Setting_Extension}" />
<TextBlock
x:Name="contentTB"
Margin="4,0,0,0"
HorizontalAlignment="Center"
VerticalAlignment="Center"
FontSize="{TemplateBinding FontSize}"
Foreground="{TemplateBinding Foreground}"
Text="{TemplateBinding Content}" />
</StackPanel>
</Border>
</ControlTemplate>
<Style x:Key="NomalBtn" TargetType="Button">
<Setter Property="Width" Value="100" />
<Setter Property="Height" Value="30" />
<Style.Triggers>
<Trigger Property="Content" Value="未安装">
<Setter Property="Template" Value="{StaticResource UnInstallTemplate}" />
</Trigger>
<Trigger Property="Content" Value="已安装">
<Setter Property="Template" Value="{StaticResource InstalledTemplate}" />
</Trigger>
</Style.Triggers>
</Style>
</Window.Resources>
<Grid>
<Button
x:Name="btn"
Click="Button_Click"
Content="未安装"
Style="{StaticResource NomalBtn}" />
</Grid>
</Window>
MainWindow.cs
using System.Windows;
namespace WPF_ButtonTemplate
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
if (string.Equals(btn.Content, "未安装"))
btn.Content = "已安装";
else
btn.Content = "未安装";
}
}
}
项目免费下载地址: