【问题标题】:Use ResourceDictionary with other Styles in WPF将 ResourceDictionary 与 WPF 中的其他样式一起使用
【发布时间】:2018-12-25 17:24:11
【问题描述】:

我正在尝试在我的 WPF 程序中使用 ResourceDictionary 和 Style。当我在<Window.Resources> 中只有 ResourceDictionary 时,一切正常,但只要我添加 <Style>,程序就会显示字典的“找不到资源”,并且出现错误“无法解析资源“PlusMinusExpander”。”

<Window.Resources>
    <Style x:Key="CurrencyCellStyle" TargetType="{x:Type DataGridCell}">
        <Setter Property="Foreground" Value="#dddddd" />
        <Style.Triggers>
            <Trigger Property="IsSelected" Value="True">
                <Setter Property="Background" Value="Transparent"/>
                <Setter Property="BorderBrush" Value="Transparent"/>
            </Trigger>
        </Style.Triggers>
    </Style>

    <ResourceDictionary x:Key="hello" Source="Assets/PlusMinusExpanderStyles.xaml" />
</Window.Resources>


<Expander Header="Plus Minus Expander" Style="{StaticResource PlusMinusExpander}" HorizontalAlignment="Right" Width="292">
    <Grid Background="Transparent">
        <TextBlock>Item1</TextBlock>
     </Grid>
</Expander>

即使在添加 CurrencyCellStyle 样式后,我也希望能够做到 Style="{StaticResource PlusMinusExpander}"。 我在网上看到过类似的问题,但他们的解决方案都没有对我有用。有没有办法同时使用 Style 和 ResourceDictionary?

【问题讨论】:

    标签: c# wpf xaml resourcedictionary


    【解决方案1】:

    Window.Resources属性的类型是ResourceDictionary,所以不能把两种不同类型的XAML元素当作兄弟。相反,您应该:

    • 将单独的ResourceDictionary 放入Window.Resources 属性中,并将Style 写入ResourceDictionary 内。
    • ResourceDictionary 中删除x:Key 属性。

    <FrameworkElement.Resources>
        <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
                <ResourceDictionary Source="Assets/PlusMinusExpanderStyles.xaml" />
            </ResourceDictionary.MergedDictionaries>
            <Style x:Key="CurrencyCellStyle" TargetType="{x:Type DataGridCell}">
                <Setter Property="Foreground" Value="#dddddd" />
                <Style.Triggers>
                    <Trigger Property="IsSelected" Value="True">
                        <Setter Property="Background" Value="Transparent"/>
                        <Setter Property="BorderBrush" Value="Transparent"/>
                    </Trigger>
                </Style.Triggers>
            </Style>
        </ResourceDictionary>
    </FrameworkElement.Resources>
    

    【讨论】:

    • 感谢您的解释。这对我来说非常有效。
    • 很高兴它能帮到你。
    猜你喜欢
    • 2012-02-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-26
    • 2017-07-24
    • 1970-01-01
    • 2013-04-03
    • 1970-01-01
    相关资源
    最近更新 更多