我想为我的应用程序中的所有切换按钮创建一个样式。除了加载不同的图像外,它们具有所有相同的行为。我的想法是在按下按钮时更改代码中的资源“ToggleButtonImg_Disabled”、“ToggleButtonImg_IsMouseOver”、“ToggleButtonImg_IsPressed”和“ToggleButtonImg_IsChecked”。但是它不起作用......有人可以帮助我!提前致谢!
XAML
<Image Width="20" Source="Resources/Images/icon_stop.png" x:Key="ToggleButtonImg_Disabled" />
<Image Width="20" Source="Resources/Images/icon_stop.png" x:Key="ToggleButtonImg_IsMouseOver" />
<Image Width="20" Source="Resources/Images/icon_stop.png" x:Key="ToggleButtonImg_IsPressed" />
<Image Width="20" Source="Resources/Images/icon_stop.png" x:Key="ToggleButtonImg_IsChecked" />
<Style TargetType="{x:Type ToggleButton}" x:Key="ToggleButtonStyle">
<Setter Property="SnapsToDevicePixels" Value="true"/>
<Setter Property="OverridesDefaultStyle" Value="true"/>
<Setter Property="Content" Value="{DynamicResource ToggleButtonImg_Disabled}" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="ToggleButton">
<Border
x:Name="CustomControlTemplate"
CornerRadius="2"
BorderThickness="1">
<ContentPresenter
Margin="2"
HorizontalAlignment="Center"
VerticalAlignment="Center"
RecognizesAccessKey="True"/>
</Border>
<ControlTemplate.Triggers>
<Trigger Property="IsMouseOver" Value="true">
<Setter Property="Content" Value="{DynamicResource ToggleButtonImg_IsMouseOver}" />
</Trigger>
<Trigger Property="IsPressed" Value="true">
<Setter Property="Content" Value="{DynamicResource ToggleButtonImg_IsPressed}" />
</Trigger>
<Trigger Property="IsChecked" Value="True">
<Setter Property="Content" Value="{DynamicResource ToggleButtonImg_IsChecked}" />
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
代码
//设置按钮按下时的图片
BitmapImage img = new BitmapImage();
img.BeginInit();
img.UriSource = new Uri(@"Resources/Images/icon_play.png", UriKind.Relative);
img.EndInit();
_receiver.Resources["ToggleButtonImg_IsChecked"] = img;
我的代码已更新(仅 XAML):
<Style TargetType="{x:Type ToggleButton}" x:Key="ToggleButtonStyle">
<Setter Property="SnapsToDevicePixels" Value="true"/>
<Setter Property="OverridesDefaultStyle" Value="true"/>
<Setter Property="Content" Value="{DynamicResource ToggleButtonImg_Disabled}" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="ToggleButton">
<Image x:Name="CustomControlTemplate"
Width="20"
Source="Resources/Images/icon_stop.png"
/>
<ControlTemplate.Triggers>
<Trigger Property="IsMouseOver" Value="true">
<Setter TargetName="CustomControlTemplate" Property="Source" Value="{DynamicResource ToggleButtonImg_IsMouseOver}" />
</Trigger>
<Trigger Property="IsPressed" Value="true">
<Setter TargetName="CustomControlTemplate" Property="Source" Value="{DynamicResource ToggleButtonImg_IsPressed}" />
</Trigger>
<Trigger Property="IsChecked" Value="True">
<Setter TargetName="CustomControlTemplate" Property="Source" Value="{DynamicResource ToggleButtonImg_IsChecked}" />
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>