c# - 将相同样式应用于 XAML 页面中的多个按钮
问题描述
我试图在单击按钮时向按钮添加背景颜色,并在一段时间后恢复其原始颜色。我尝试创建一个ResourceDictionary.xaml
并添加我的样式集并将其引用添加到 XAML 页面。我的代码似乎有问题。如果我将样式直接添加到按钮标签中,它可以工作.. 但不是通过ResourceDictionary
. 请帮忙。
资源字典.xaml
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:FantasyPlay">
<Style TargetType="Button">
<Setter Property="Background" Value="Gainsboro" />
<Style.Triggers>
<Trigger Property="IsPressed" Value="True">
<Trigger.EnterActions>
<BeginStoryboard>
<Storyboard>
<ColorAnimation Storyboard.TargetProperty="(Button.Background).(SolidColorBrush.Color)" From="Orange" To="Gainsboro" Duration="0:0:0.50" AutoReverse="True" />
<ColorAnimation Storyboard.TargetProperty="(Button.Background).(SolidColorBrush.Color)" From="Gainsboro" To="Orange" Duration="0:0:0.1" AutoReverse="True" />
</Storyboard>
</BeginStoryboard>
</Trigger.EnterActions>
</Trigger>
</Style.Triggers>
</Style>
MyXAML:
我像这样引用它
<Window.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="ResourceDictionary.xaml"/>
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</Window.Resources>
解决方案
WPF 控件有一个模板。
按钮的模板做了很多事情,其中之一是鼠标悬停效果。这会干扰你的造型。
这是一种与您的样式类似的样式,但它替换了按钮模板,因此您可以在鼠标悬停时看到效果。
我使用的是红色而不是 Gainsboro,所以这可能不是一个完整的剪切和粘贴解决方案,但可以帮助您入门。
<Style TargetType="Button">
<Setter Property="Background" Value="Red"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="Button">
<Border Name="border"
BorderThickness="1"
Padding="4,2"
BorderBrush="DarkGray"
CornerRadius="3"
Background="{TemplateBinding Background}">
<ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center" />
</Border>
<ControlTemplate.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter TargetName="border" Property="BorderBrush" Value="Black" />
</Trigger>
<Trigger Property="IsPressed" Value="True">
<Trigger.EnterActions>
<BeginStoryboard>
<Storyboard>
<ColorAnimation Storyboard.TargetProperty="(Button.Background).(SolidColorBrush.Color)"
To="Orange"
Duration="0:0:1"
AutoReverse="True"
FillBehavior="Stop" />
</Storyboard>
</BeginStoryboard>
</Trigger.EnterActions>
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</ResourceDictionary>
显然,这取代了您在资源字典中的内容。首先保留原件的副本。
推荐阅读
- javascript - `this` 的属性在 setTimeout 中未定义
- node.js - 错误:已知 npm 不能在 Node.js v 上运行
- google-apps-script - 随机字符串生成器随机化太频繁
- visual-studio-code - VSCode 按名称终止任务
- java - 二叉树节点计算的递归方法
- c# - 无法从“System.Transactions.IsolationLevel”转换为“System.Data.IsolationLevel”
- ios - iOS - 大小类的不同堆栈视图
- c++ - 逆向工程项目到图形 UML 图
- c++ - Eigen3:定义一个可变大小的矩阵
- dart - Dart 中的“const”和“final”关键字有什么区别?