在 WPF 中将 ResourceDictionary 与其他样式一起使用

shr*_*eya 3 c# wpf xaml resourcedictionary

我正在尝试在我的 WPF 程序中使用 ResourceDictionary 和 Style。当我只有 ResourceDictionary 时,<Window.Resources>一切工作正常,但一旦我添加一个<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>
Run Code Online (Sandbox Code Playgroud)

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

wal*_*rlv 6

Window.Resources属性的类型是ResourceDictionary,因此不能将两个不同类型的 XAML 元素视为兄弟。相反,您应该:

  • 将一个分隔符放入属性ResourceDictionaryWindow.Resources并在Style里面写入ResourceDictionary
  • x:Key从 中删除该属性ResourceDictionary

<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>
Run Code Online (Sandbox Code Playgroud)