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

for*_*yez 12 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>
Run Code Online (Sandbox Code Playgroud)

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

Ken*_*art 13

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

<ContentPresenter Content="{TemplateBinding Content1}"/>
<ContentPresenter Content="{TemplateBinding Content2}"/>
Run Code Online (Sandbox Code Playgroud)

控件本身应该为内容公开两个属性,并使用以下命令设置默认值ContentPropertyAttribute:

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

  • 您可以使用ContentSource属性更直接地执行此操作 - 这样做的好处还在于支持内容的模板和模板选择器. (2认同)
  • @foreyez:我假设你没有从`ContentControl`继承.顺便说一句,根据您的具体要求,您可能只需使用`HeaderedContentControl`即可. (2认同)

小智 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>
Run Code Online (Sandbox Code Playgroud)