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

标签 c# .net wpf data-binding wpf-controls

我有一个 View 框:

<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>

但是,只有一个按钮有椭圆(viewbox)

如何让所有的按钮都有/显示椭圆??

最佳答案

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

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

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

关于c# - Button Style 的内容只出现在一个 Button 实例中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42924151/

相关文章:

c# - 如何写入 "*.bat"文件?

c# - 带有 2 个文本的按钮,通过 controltemplate 绑定(bind)

c# - 降低绑定(bind)DataGrid的刷新率

c# optimizing cycle working with big numbers 工作大数

c# - Request.Browser.IsMobileDevice 不适用于 iPadAir2 和 iOS 13.0.1

c# - 单击时捕获并保存屏幕截图 - Windows C#

c# - 在 C# 中使用 Monad 的引人注目的场景是什么

c# - 构建唯一 ID 及其计数集合的最佳方式

c# - PrintSystemJobInfo.JobStream 坏了吗?

c# - 如何在 WPF 的第二个屏幕中启动第二个应用程序?