Content of a Button Style appears only in one Button instance

后端 未结 3 1008
一生所求
一生所求 2020-11-30 15:51

I have a Viewbox:


  
    

        
相关标签:
3条回答
  • 2020-11-30 16:19

    Setting the x:Shared attribute of the ViewBox to false as suggested by @ASh will indeed work but why don't you just include the ViewBox in the ControlTemplate like this?

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

    A template is a template and a control instance is an instance.

    0 讨论(0)
  • 2020-11-30 16:24

    I think a good approach is to use DataTemplate. So you will have

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

    And for style

    <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>
    
    0 讨论(0)
  • 2020-11-30 16:31

    Viewbox is FrameworkElement which cannot belong to multiple parents. Every time buttons request a resource {StaticResource SampleViewbox} they get the same instance.

    to change that behavior add x:Shared="False" attribute

    <Viewbox x:Key="SampleViewbox" x:Shared="False">
    
    0 讨论(0)
提交回复
热议问题