按钮样式的内容仅出现在一个按钮实例中

Sab*_*abz 1 .net c# data-binding wpf wpf-controls

我有一个视图框:

<Viewbox x:Key="SampleViewbox" >
  <Grid>
    <Ellipse Stroke="#e2e2e0" StrokeThickness="6" Fill="#d5273e" Width="128" Height="128"/>
  </Grid>
</Viewbox>
Run Code Online (Sandbox Code Playgroud)

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

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

现在我用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>
Run Code Online (Sandbox Code Playgroud)

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

我怎样才能让所有按钮都有/显示椭圆?

ASh*_*ASh 5

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

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

<Viewbox x:Key="SampleViewbox" x:Shared="False">
Run Code Online (Sandbox Code Playgroud)


Iva*_*kov 5

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

<DataTemplate x:Key="SampleViewbox">
    <Viewbox>
        <Grid>
            <Ellipse
                    Width="128"
                    Height="128"
                    Fill="#d5273e"
                    Stroke="#e2e2e0"
                    StrokeThickness="6" />
        </Grid>
    </Viewbox>
</DataTemplate>
Run Code Online (Sandbox Code Playgroud)

以及风格

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