首页 > 解决方案 > WPF Window.Resources VS Application.Resources

问题描述

我在 Window.Resources 中对我的“MenuItem”样式创建了一些动画

        <Style TargetType="MenuItem">
        <Setter Property="Foreground" Value="White"/>
        <Setter Property="FontSize" Value="10"/>
        <Setter Property="Background">
            <Setter.Value>
                <SolidColorBrush Color="#2e3137"/>
            </Setter.Value>
        </Setter>
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type MenuItem}">
                    <Border x:Name="Bd" Padding="17,0,17,0" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Background="#2e3137" SnapsToDevicePixels="True" Uid="Border_38">
                        <ContentPresenter x:Name="ContentPresenter"  Content="{TemplateBinding Header}" Grid.Column="1" ContentSource="Header" Margin="{TemplateBinding Padding}" RecognizesAccessKey="True" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" Uid="ContentPresenter_33"/>
                    </Border>
                    <ControlTemplate.Triggers>
                        <EventTrigger RoutedEvent="MenuItem.MouseEnter">
                            <BeginStoryboard>
                                <Storyboard>
                                    <ColorAnimation To="Gray" Storyboard.TargetProperty="(MenuItem.Background).(SolidColorBrush.Color)" Duration="0:0:0.3"/>
                                </Storyboard>
                            </BeginStoryboard>
                        </EventTrigger>
                        <EventTrigger RoutedEvent="MenuItem.MouseLeave">
                            <BeginStoryboard>
                                <Storyboard>
                                    <ColorAnimation To="Transparent" Storyboard.TargetProperty="(MenuItem.Background).(SolidColorBrush.Color)" Duration="0:0:0.3"/>
                                </Storyboard>
                            </BeginStoryboard>
                        </EventTrigger>
                        <Trigger Property="IsEnabled" Value="False">
                            <Setter Property="Opacity" TargetName="Bd" Value="0.56"/>
                        </Trigger>
                    </ControlTemplate.Triggers>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>

这个效果很好。但后来我意识到我需要将样式移动到 Application.Resources,因为我需要在不同的窗口中使用这种样式,但是当我移动它时,动画停止工作并出现错误:'Background' 属性不指向路径中的 DependencyObject'( 0).(1)'。那么这些资源有什么区别以及如何解决我的问题呢?谢谢。

UPD:发现问题不是菜单项而是标签,这很奇怪,因为我只将此样式设置为标签

    <Style TargetType="Label">
        <Setter Property="Foreground" Value="White"/>
        <Setter Property="FontSize" Value="14"/>
    </Style>

标签: .netwpf

解决方案


推荐阅读