【问题标题】:WPF: Multiple content presenters in a custom control?WPF:自定义控件中的多个内容演示者?
【发布时间】:2011-09-28 00:37:00
【问题描述】:

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

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

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

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

【问题讨论】:

    标签: c# wpf xaml


    【解决方案1】:

    模板可以像这样绑定单独的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
    }
    

    【讨论】:

    • 您可以通过使用 ContentSource 属性更直接地执行此操作 - 这还具有支持内容模板和模板选择器的优势。
    • 肯特,我不需要设置 ContentProperty 属性,因为它已经设置为“内容”。我只需要为“Content2”设置另一个依赖属性并将其绑定到另一个内容演示者,但感谢您将我指向正确的目录
    • @foreyez:我假设你没有从 ContentControl 继承。顺便说一句,根据您的具体要求,您可能只需使用HeaderedContentControl
    【解决方案2】:

    您可以将“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>
    

    【讨论】:

      【解决方案3】:

      这是另一个不需要制作自定义控件并且比执行 ItemsControl 更类型安全的选项(如果您想要类型安全......也许不是):

      ...使用附加属性!

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-01-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多