Button Style 的内容只出现在一个 Button 实例中

Content of a Button Style appears only in one Button instance

我有一个 Viewbox:

<Viewbox x:Key="SampleViewbox" >
  <Grid>
    <Ellipse Stroke="#e2e2e0" StrokeThickness="6" Fill="#d5273e" Width="128" Height="128"/>
  </Grid>
</Viewbox>

然后我将其包含在如下样式中:

<Style x:Key="SampleStyle" TargetType="{x:Type Button}">
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type Button}">
                <Border Background="Transparent" >
                    <ContentPresenter Content="{StaticResource SampleViewbox}"/>
                </Border>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

现在我用 SampleStyle 创建了许多按钮

<Grid>   
    <StackPanel>
       <Button Style="{StaticResource SampleStyle}" Height="50" Width="50"></Button>
       <Button Style="{StaticResource SampleStyle}" Height="80" Width="80"></Button>
       <Button Style="{StaticResource SampleStyle}" Height="20" Width="20"></Button>  
    </StackPanel>
</Grid>

但是,只有一个按钮有椭圆(视图框)

如何让所有的按钮 have/show 变成椭圆形??

Viewbox 是不能属于多个父级的 FrameworkElement。每次按钮请求资源时 {StaticResource SampleViewbox} 他们得到相同的实例。

要更改该行为,请添加 x:Shared="False" 属性

<Viewbox x:Key="SampleViewbox" x:Shared="False">

按照@ASh 的建议将 ViewBoxx:Shared 属性设置为 false 确实有效,但为什么不将 ViewBox 包含在ControlTemplate像这样?

<Style x:Key="SampleStyle" TargetType="{x:Type Button}">
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type Button}">
                <Border Background="Transparent" >
                    <Viewbox>
                        <Grid>
                            <Ellipse Stroke="#e2e2e0" StrokeThickness="6" Fill="#d5273e" Width="128" Height="128"/>
                        </Grid>
                    </Viewbox>
                </Border>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

模板是模板,控件实例是实例。

我认为一个好的方法是使用 DataTemplate。 所以你会有

<DataTemplate x:Key="SampleViewbox">
    <Viewbox>
        <Grid>
            <Ellipse
                    Width="128"
                    Height="128"
                    Fill="#d5273e"
                    Stroke="#e2e2e0"
                    StrokeThickness="6" />
        </Grid>
    </Viewbox>
</DataTemplate>

以及风格

<Style x:Key="SampleStyle" TargetType="{x:Type Button}">
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type Button}">
                <Border Background="Transparent">
                    <ContentPresenter ContentTemplate="{StaticResource SampleViewbox}" />
                </Border>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>