这是App.xaml中的Style
:
<Style x:Key="numButton" TargetType="{x:Type Button}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type Button}">
<Image x:Name="img" Style="{DynamicResource imgDefault}"></Image>
<ControlTemplate.Triggers>
<Trigger Property="IsPressed" Value="true">
<Setter Property="Source" TargetName="img" Value="img/1_push.png"></Setter>
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
<Setter Property="Cursor" Value="Hand"></Setter>
</Style>
<Style x:Key="imgDefault" TargetType="{x:Type Image}">
<Setter Property="Source" Value="img/0.png"></Setter>
</Style>
我有多个按钮作为数字(0-9),我想为所有这些使用一种风格,以避免更多的文字输入。目前,我可以更改每个按钮的默认背景:
<Button Name="btn1" Grid.Row="0" Grid.Column="0" Style="{DynamicResource numButton}" Foreground="White">
<Button.Resources>
<Style x:Key="imgDefault" TargetType="{x:Type Image}">
<Setter Property="Source" Value="img/1.png"></Setter>
</Style>
</Button.Resources>
</Button>
所以现在我想知道是否可以在App.xaml中为每个按钮更改Value="img/1_push.png"
?例如,当按下2
时,我希望它的背景为2_push.png
。
提前致谢。
答案 0 :(得分:1)
您可以使用两个依赖项属性创建自定义Button类:
<强> ImageButton.cs:强>
namespace WpfApplication2
{
public class ImageButton : System.Windows.Controls.Button
{
public static readonly DependencyProperty DefaultImageProperty =
DependencyProperty.Register("DefaultImage", typeof(Uri), typeof(ImageButton));
public Uri DefaultImage
{
get { return (Uri)GetValue(DefaultImageProperty); }
set { SetValue(DefaultImageProperty, value); }
}
public static readonly DependencyProperty PressedImageProperty =
DependencyProperty.Register("PressedImage", typeof(Uri), typeof(ImageButton));
public Uri PressedImage
{
get { return (Uri)GetValue(PressedImageProperty); }
set { SetValue(PressedImageProperty, value); }
}
}
}
<强> App.xaml中:强>
<Application x:Class="WpfApplication2.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WpfApplication2"
StartupUri="Window1.xaml">
<Application.Resources>
<Style TargetType="local:ImageButton">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type local:ImageButton}">
<Image x:Name="img" Source="{Binding DefaultImage,RelativeSource={RelativeSource TemplatedParent}, FallbackValue=img/0.png, TargetNullValue=img/0.png}" />
<ControlTemplate.Triggers>
<Trigger Property="IsPressed" Value="true">
<Setter Property="Source" TargetName="img" Value="{Binding PressedImage, RelativeSource={RelativeSource TemplatedParent}, FallbackValue=img/1_push.png, TargetNullValue=img/1_push.png}"></Setter>
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
<Setter Property="Cursor" Value="Hand"></Setter>
</Style>
</Application.Resources>
用法:
<local:ImageButton x:Name="btn1" Grid.Row="0" Grid.Column="0" Foreground="White"
DefaultImage="img/1.png" PressedImage="2_push.png"/>
这是一种更加清洁和灵活的方法。