开发者

Naming Control Contained Within Custom WPF GroupBox

I've got a custom GroupBox control that essentially does nothing more than apply a style

<GroupBox x:Class="SharedResources.Controls.StyledGroupBox"
          xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
          xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <GroupBox.Style>
        <Style TargetType="{x:Type GroupBox}">
            <Setter Property="BorderBrush" Value="#D5DFE5"/>
            <Setter Property="BorderThickness" Value="1"/>
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="{x:Type GroupBox}">
                        ...
                            <ContentPresenter Grid.ColumnSpan="2" Grid.Column="1" Grid.Row="2" 
                                              Margin="{TemplateBinding Padding}" 
                                              SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}"/>

                        </Grid>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>
    </GroupBox.Style>
</GroupBox>

The problem is that when I come to use 开发者_StackOverflowthis, if I set x:Name property of the content of the StyledGroupBox, then I get the following error:

Cannot set Name attribute value 'name' on element ''. '' is under the scope of element 'StyledGroupBox', which already had a name registered when it was defined in another scope

Any ideas how I can resolve this?


Don't use a UserControl just to define a Style (I'd love to know where this practice comes from because I've seen an explosion of it recently). Instead, create the Style as a resource in its own right and apply it to GroupBoxes as desired:

<Style TargetType="{x:Type GroupBox}">
    <Setter Property="BorderBrush" Value="#D5DFE5"/>
    <Setter Property="BorderThickness" Value="1"/>
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type GroupBox}">...
                <ContentPresenter Grid.ColumnSpan="2" Grid.Column="1" Grid.Row="2"                                                Margin="{TemplateBinding Padding}"                                                SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}"/>
                </Grid>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

...

<GroupBox>
  Will inherit the above style.
</GroupBox>


If anyone is trying to make this work (for something more/other than styles), see: How to create a WPF UserControl with NAMED content

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜