关于WPF资源/样式的问题&;范围

关于WPF资源/样式的问题&;范围,wpf,Wpf,我刚刚开始WPF,不知道为什么会这样 <Window ...> <Window.Resources> <Style x:Name="buttonStyle"> <Style.Setters> <Setter Property="Button.FontWeight" Value="Bold" /> <Setter Prop

我刚刚开始WPF,不知道为什么会这样

<Window ...>
    <Window.Resources>
        <Style x:Name="buttonStyle">
            <Style.Setters>
                <Setter Property="Button.FontWeight" Value="Bold" />
                <Setter Property="Button.Foreground" Value="Aqua" />
            </Style.Setters>
        </Style>
    </Window.Resources>
    <Grid>
        <StackPanel>
            <Button ... Style="{StaticResource buttonStyle}" />
        </StackPanel>
    </Grid>
</Window>

但这失败了

<Window ...>
    <Window.Resources>
        <Style x:Name="buttonStyle">
            <Style.Setters>
                <Setter Property="Button.FontWeight" Value="Bold" />
                <Setter Property="Button.Foreground" Value="Aqua" />
            </Style.Setters>
        </Style>
    </Window.Resources>
    <Grid>
        <StackPanel ...>
            <StackPanel.Resources>
                <Style x:Name="buttonStyle2">
                    <Setter Property="Button.Foreground" Value="Red" />
                </Style>
            </StackPanel.Resources>
            <Button ... Style="{StaticResource buttonStyle}" />
            <Button ... Style="{StaticResource buttonStyle2}" />
        </StackPanel>
    </Grid>
</Window>

错误是

  • 无法解析资源“buttonStyle2”
  • 无法解析资源“buttonStyle”

按钮样式
在第1个代码中解析ok(不带第2个按钮)

arr。。。我的错,我应该使用
x:Key
而不是
x:Name