WPF:自定义控件中的多个内容演示者?

时间:2011-02-18 18:08:57

标签: c# wpf xaml

我正在尝试使用一个自定义控件,该控件需要由子控件定义2个或更多XAML区域 - 从该控件继承。我想知道是否有一种方法可以定义多个内容提供者和一个充当默认内容提供者的方法

<MyControl>
      <MyControl.MyContentPresenter2>
           <Button Content="I am inside the second content presenter!"/>
      </MyControl.MyContentPresenter2>

      <Button Content="I am inside default content presenter" />
</MyControl>

这可能,我如何在自定义控件的模板中定义它?

3 个答案:

答案 0 :(得分:13)

模板可以像这样绑定单独的ContentPresenter个实例(我这里只设置了一个属性,但你可能想要设置其他属性):

<ContentPresenter Content="{TemplateBinding Content1}"/>
<ContentPresenter Content="{TemplateBinding Content2}"/>

控件本身应公开内容的两个属性,并使用ContentPropertyAttribute设置默认值:

[ContentProperty("Content1")]
public class MyControl : Control
{
    // dependency properties for Content1 and Content2
    // you might also want Content1Template, Content2Template, Content1TemplateSelector, Content2TemplateSelector
}

答案 1 :(得分:6)

您可以将“ItemsControl”与自定义模板一起使用。

<ItemsControl>
    <ItemsControl.Style>
        <Style TargetType="ItemsControl">
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate>
                        <StackPanel Orientation="Horizontal">
                            <ContentControl Content="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=Items[0]}"/>
                            <ContentControl Content="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=Items[1]}"/>
                            <ContentControl Content="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=Items[2]}"/>
                        </StackPanel>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>
    </ItemsControl.Style>
    <TextBlock Text="Item 1"/>
    <TextBlock Text="Item 2"/>
    <TextBlock Text="Item 3"/>
</ItemsControl>

答案 2 :(得分:3)

这是另一个不需要制作自定义控件的选项,比使用ItemsControl更安全(如果类型安全是你想要的......也许不是):

...使用附属物!

创建适当类型的附加属性。我们碰巧需要一个文本控件,所以我做了一个字符串TextContent附加属性。然后从模板创建一个TemplateBinding,当在Xaml中实例化时,也将它设置在那里。很好地工作。