开发者

Embedding content within a UserControl instance

I have a WPF UserControl, which is simply a Label for whatever else it goes with. E.g, a Label for a 开发者_运维百科TextBox. I want to place this TextBox inside the LabeledControl markup, like this:

<LabeledControl Label="First name">
  <TextBox Binding="{FirstName}" />
</LabeledControl>

The reason I want to do this is to style the way controls and their labels look.

I can't find an obvious way to do this. Am I even approaching this the right way? Should I be looking at templates instead?


I'd say that a better option would be to use the built-in HeaderedContentControl, which allows you to specify a Header (your label) and a Content (your text box) property.

You can then specify a ControlTemplate for the HeaderedContentControl to alter the appearance:

<Style x:Key="MyLabelledItemStyle" TargetType="HeaderedContentControl">
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="HeaderedContentControl">
                <StackPanel Orientation="Horizontal">
                    <ContentControl Content="{TemplateBinding Header}" Margin="2" />
                    <ContentControl Content="{TemplateBinding Content}" Margin="2" />
                </StackPanel>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

This example just concatenates the two components horizontally in a StackPanel, but you could do something more complicated if required.

You can then use this in XAML as below:

<HeaderedContentControl Style="{StaticResource MyLabelledItemStyle}" Header="First Name">
    <TextBox Text="{Binding FirstName}" />
</HeaderedContentControl>
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜