在WPF中如何使用ResourceDictionary与其他Styles一起?

3

我正在尝试在我的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}"。我在网上看到过类似的问题,但它们的解决方案都还没有对我起作用。是否有一种方法可以同时使用样式和ResourceDictionary?

1个回答

6
Window.Resources属性的类型是ResourceDictionary,因此不能将两种不同类型的XAML元素放在一起。相反,您应该:
  • 将一个独立的ResourceDictionary放入Window.Resources属性中,并在ResourceDictionary中编写Style
  • 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>

非常感谢您的解释。这对我来说完美地运行了。 - shreeya
我很高兴它能帮到你。 - walterlv

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接