c# - 以编程方式枚举和应用 WPF 样式

标签 c# wpf xaml storyboard styling

我有一个这样的 WPF 按钮

<Button Name="HelloWorldButton"
        Width="100"
        Height="100"
        HorizontalAlignment="Center"
        VerticalAlignment="Center"
        Style="{StaticResource TileButton}">
    Hello world
</Button>

使用 WPF 样式,我应用了如下所示的样式模板

<Style x:Key="TileButton" TargetType="Button">
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="Button">
                <Border x:Name="focusRect"
                        Margin="-6"
                        BorderThickness="6">
                    <ContentPresenter />
                    <Border.BorderBrush>
                        <SolidColorBrush x:Name="focusRectBrush" Color="Transparent" />
                    </Border.BorderBrush>
                    <VisualStateManager.VisualStateGroups>
                        <VisualStateGroup x:Name="CommonStates">
                            <VisualState x:Name="Normal" />
                            <VisualState x:Name="MouseOver">
                                <Storyboard>
                                    <ColorAnimation Duration="0"
                                                    Storyboard.TargetName="focusRectBrush"
                                                    Storyboard.TargetProperty="Color"
                                                    To="Red" />
                                </Storyboard>
                            </VisualState>
                            <VisualState x:Name="Pressed">
                                <Storyboard>
                                    <ColorAnimation Duration="0"
                                                    Storyboard.TargetName="focusRectBrush"
                                                    Storyboard.TargetProperty="Color"
                                                    To="White" />
                                </Storyboard>
                            </VisualState>
                        </VisualStateGroup>
                    </VisualStateManager.VisualStateGroups>
                </Border>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

我现在想以编程方式应用 MouseOver VisualState。我查看了 HelloWorldButton.Style 属性,但看不到任何明显的实现此目的的方法。

注意:显然,我明白,在不使用声明的 XAML 样式表的情况下,以编程方式直接向按钮添加边框是很简单的,但在我的场景中,这不是一个可行的方法。

最佳答案

终于解决了。

我正在寻找的代码很简单

VisualStateManager.GoToState(HelloWorldButton, "MouseOver", true);

关于c# - 以编程方式枚举和应用 WPF 样式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30831782/

相关文章:

c# - 让 VS2010 使用 IE9 打开 XBAP,即使 Chrome 是我的默认浏览器

c# - 根据屏幕大小调整 WPF 窗口大小

WPF 功能区按钮鼠标悬停时发光效果

windows - 如何在 Applicationbar 顶部设置元素(或让布局知道它)?

c# - FolderPicker 在 UWP Windows 10 应用程序(移动)中不起作用

c# - 确保每次使用 Dapper 访问数据库时数据库连接打开和关闭

c# - MVVM丢失,尝试将M连接到VM到V

wpf - InvokeCommandAction 未调用

c# - Makefile 正则表达式替换

c# - linq 和字符串数组