WPF:带有2个(或更多!)ContentPresenters的模板或UserControl,用于在'slots'中显示内容

时间:2009-06-22 23:47:47

标签: wpf user-controls contentpresenter

我正在开发LOB应用程序,我需要多个对话框窗口(在一个窗口中显示所有内容不是一个选项/没有意义)。

我希望我的窗口有一个用户控件来定义一些样式等,并且可以有几个插槽来插入内容 - 例如,模态对话框窗口的模板会有一个内容插槽和按钮(这样用户就可以提供带有绑定ICommands的内容和一组按钮)。

我想要这样的东西(但这不起作用):

UserControl xaml:

<UserControl x:Class="TkMVVMContainersSample.Services.Common.GUI.DialogControl"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Background="{DynamicResource {x:Static SystemColors.ControlBrushKey}}"
    >
    <DockPanel>
        <DockPanel 
            LastChildFill="False" 
            HorizontalAlignment="Stretch" 
            DockPanel.Dock="Bottom">
            <ContentPresenter ContentSource="{Binding Buttons}"/>
        </DockPanel>
        <Border 
            Background="{DynamicResource {x:Static SystemColors.WindowBrushKey}}"
            Padding="8"
            >
            <ContentPresenter ContentSource="{Binding Controls}"/>
        </Border>
    </DockPanel>
</UserControl>

这样的事情可能吗?我该如何告诉VS我的控件公开了两个内容占位符,以便我可以像这样使用它?

<Window ... DataContext="MyViewModel">

    <gui:DialogControl>
        <gui:DialogControl.Controls>
            <!-- My dialog content - grid with textboxes etc... 
            inherits the Window's DC - DialogControl just passes it through -->
        </gui:DialogControl.Controls>
        <gui:DialogControl.Buttons>
            <!-- My dialog's buttons with wiring, like 
            <Button Command="{Binding HelpCommand}">Help</Button>
            <Button Command="{Binding CancelCommand}">Cancel</Button>
            <Button Command="{Binding OKCommand}">OK</Button>
             - they inherit DC from the Window, so the OKCommand binds to MyViewModel.OKCommand
             -->
        </gui:DialogControl.Buttons>
    </gui:DialogControl>

</Window>

或许我可以将ControlTemplate用于窗口like here,但是又一次:Window只有一个内容插槽,因此它的模板只能有一个演示者,但我需要两个(如果在在这种情况下,它可能会与一个一起使用,还有其他用例会有几个内容插槽出现,只需考虑文章的模板 - 控件的用户将提供标题,(结构化)内容,作者姓名,图像。 ..)。

谢谢!

PS:如果我想并排按钮,我怎样才能将多个控件(按钮)放到StackPanel上? ListBox有ItemsSource,但StackPanel没有,并且它的Children属性是只读的 - 所以这不起作用(在usercontrol中):

<StackPanel 
    Orientation="Horizontal"
    Children="{Binding Buttons}"/> 
编辑:我不想使用绑定,因为我想将一个DataContext(ViewModel)分配给一个整个窗口(等于View),然后从插入控件'slots'的按钮绑定它的命令 - 所以在层次结构中使用任何绑定都会破坏View的DC的继承。

至于从HeaderedContentControl继承的想法 - 是的,在这种情况下它会起作用,但如果我想要三个可替换的部分呢?如何创建自己的“HeaderedAndFooteredContentControl”(或者,如果我没有,我将如何实现HeaderedContentControl)

EDIT2:好的,所以我的两个解决方案都不起作用 - 这就是原因: ContentPresenter从DataContext获取它的内容,但我需要对包含的元素进行绑定以链接到原始窗口'(UserControl的父逻辑树中)DataContext - 因为这样,当我嵌入绑定到ViewModel属性的文本框时,它没有绑定,因为继承链已经在控件中被破坏了

似乎我需要保存父级的DataContext,并将其恢复到所有控件容器的子级,但是我没有得到逻辑树中的DataContext更改的任何事件。

EDIT3:我有一个解决方案!,删除了我以前的aswers。 请参阅我的回复。

3 个答案:

答案 0 :(得分:31)

好的,我的解决方案完全没必要,以下是创建任何用户控件所需的唯一教程:

简而言之:

子类一些合适的类(或UIElement,如果不适合你) - 文件只是简单的* .cs,因为我们只定义行为,而不是控件的外观。

public class EnhancedItemsControl : ItemsControl

为'slots'添加依赖项属性(正常属性不够好,因为它只有有限的绑定支持)。酷炫的技巧:在VS中,写下propdp并按Tab键展开片段:):

public object AlternativeContent
{
    get { return (object)GetValue(AlternativeContentProperty); }
    set { SetValue(AlternativeContentProperty, value); }
}

// Using a DependencyProperty as the backing store for AlternativeContent.  This enables animation, styling, binding, etc...
public static readonly DependencyProperty AlternativeContentProperty =
    DependencyProperty.Register("AlternativeContent" /*name of property*/, typeof(object) /*type of property*/, typeof(EnhancedItemsControl) /*type of 'owner' - our control's class*/, new UIPropertyMetadata(null) /*default value for property*/);

为设计师添加属性(因为您正在创建所谓的无外观控件),这样我们就知道我们需要在模板中使用名为PART_AlternativeContentPresenter的ContentPresenter

[TemplatePart(Name = "PART_AlternativeContentPresenter", Type = typeof(ContentPresenter))]
public class EnhancedItemsControl : ItemsControl

提供一个静态构造函数,告诉WPF样式系统我们的类(没有它,不会应用以我们的新类型为目标的样式/模板):

static EnhancedItemsControl()
{
    DefaultStyleKeyProperty.OverrideMetadata(
        typeof(EnhancedItemsControl),
        new FrameworkPropertyMetadata(typeof(EnhancedItemsControl)));
}

如果您想从模板中对ContentPresenter执行某些操作,可以通过重写OnApplyTemplate方法来执行此操作:

//remember that this may be called multiple times if user switches themes/templates!
public override void OnApplyTemplate()
{
    base.OnApplyTemplate(); //always do this

    //Obtain the content presenter:
    contentPresenter = base.GetTemplateChild("PART_AlternativeContentPresenter") as ContentPresenter;
    if (contentPresenter != null)
    {
        // now we know that we are lucky - designer didn't forget to put a ContentPresenter called PART_AlternativeContentPresenter into the template
        // do stuff here...
    }
}

提供默认模板:始终在ProjectFolder / Themes / Generic.xaml中(我的独立项目包含所有自定义通用的wpf控件,然后从其他解决方案中引用)。这只是系统将为您的控件查找模板的地方,因此在此处为项目中的所有控件添加默认模板: 在此片段中,我定义了一个新的ContentPresenter,它显示了AlternativeContent附加属性的值。注意语法 - 我也可以使用 Content="{Binding AlternativeContent, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type WPFControls:EnhancedItemsControl}}}"Content="{TemplateBinding AlternativeContent}",但如果您在模板中定义模板(例如ItemPresenters的样式设置所必需),前者将起作用。

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:WPFControls="clr-namespace:MyApp.WPFControls"
    >

    <!--EnhancedItemsControl-->
    <Style TargetType="{x:Type WPFControls:EnhancedItemsControl}">
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type WPFControls:EnhancedItemsControl}">
                    <ContentPresenter 
                        Name="PART_AlternativeContentPresenter"
                        Content="{Binding AlternativeContent, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type WPFControls:EnhancedItemsControl}}}" 
                        DataContext="{Binding DataContext, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type WPFControls:EnhancedItemsControl}}}"
                        />
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>

</ResourceDictionary>

Voila,您刚刚制作了第一个无形的UserControl(为更多'内容插槽'添加了更多内容提供者和依赖属性)。

答案 1 :(得分:4)

Hasta la victoria siempre!

我带来了工作解决方案(首先在互联网上,在我看来:))

棘手的DialogControl.xaml.cs - 见评论:

public partial class DialogControl : UserControl
{
    public DialogControl()
    {
        InitializeComponent();

        //The Logical tree detour:
        // - we want grandchildren to inherit DC from this (grandchildren.DC = this.DC),
        // but the children should have different DC (children.DC = this),
        // so that children can bind on this.Properties, but grandchildren bind on this.DataContext
        this.InnerWrapper.DataContext = this;
        this.DataContextChanged += DialogControl_DataContextChanged;
        // need to reinitialize, because otherwise we will get static collection with all buttons from all calls
        this.Buttons = new ObservableCollection<FrameworkElement>();
    }


    void DialogControl_DataContextChanged(object sender, DependencyPropertyChangedEventArgs e)
    {
        /* //Heading is ours, we want it to inherit this, so no detour
        if ((this.GetValue(HeadingProperty)) != null)
            this.HeadingContainer.DataContext = e.NewValue;
        */

        //pass it on to children of containers: detours
        if ((this.GetValue(ControlProperty)) != null)
            ((FrameworkElement)this.GetValue(ControlProperty)).DataContext = e.NewValue;

        if ((this.GetValue(ButtonProperty)) != null)
        {
            foreach (var control in ((ObservableCollection<FrameworkElement>) this.GetValue(ButtonProperty)))
            {
                control.DataContext = e.NewValue;
            }
        }
    }

    public FrameworkElement Control
    {
        get { return (FrameworkElement)this.GetValue(ControlProperty); } 
        set { this.SetValue(ControlProperty, value); }
    }

    public ObservableCollection<FrameworkElement> Buttons
    {
        get { return (ObservableCollection<FrameworkElement>)this.GetValue(ButtonProperty); }
        set { this.SetValue(ButtonProperty, value); }
    }

    public string Heading
    {
        get { return (string)this.GetValue(HeadingProperty); }
        set { this.SetValue(HeadingProperty, value); }
    }

    public static readonly DependencyProperty ControlProperty =
            DependencyProperty.Register("Control", typeof(FrameworkElement), typeof(DialogControl));
    public static readonly DependencyProperty ButtonProperty =
            DependencyProperty.Register(
                "Buttons",
                typeof(ObservableCollection<FrameworkElement>),
                typeof(DialogControl),
                //we need to initialize this for the designer to work correctly!
                new PropertyMetadata(new ObservableCollection<FrameworkElement>()));
    public static readonly DependencyProperty HeadingProperty =
            DependencyProperty.Register("Heading", typeof(string), typeof(DialogControl));
}

DialogControl.xaml(无变化):

<UserControl x:Class="TkMVVMContainersSample.Views.Common.DialogControl"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Background="{DynamicResource {x:Static SystemColors.ControlBrushKey}}"
    >
    <DockPanel x:Name="InnerWrapper">
        <DockPanel 
            LastChildFill="False" 
            HorizontalAlignment="Stretch" 
            DockPanel.Dock="Bottom">
            <ItemsControl
                x:Name="ButtonsContainer"
                ItemsSource="{Binding Buttons}"
                DockPanel.Dock="Right"
                >
                <ItemsControl.ItemTemplate>
                    <DataTemplate>
                        <Border Padding="8">
                            <ContentPresenter Content="{TemplateBinding Content}" />
                        </Border>
                    </DataTemplate>
                </ItemsControl.ItemTemplate>
                <ItemsControl.ItemsPanel>
                    <ItemsPanelTemplate>
                        <StackPanel Orientation="Horizontal" Margin="8">
                        </StackPanel>
                    </ItemsPanelTemplate>
                </ItemsControl.ItemsPanel>
            </ItemsControl>
        </DockPanel>
        <Border 
            Background="{DynamicResource {x:Static SystemColors.WindowBrushKey}}"
            Padding="8,0,8,8"
            >
            <StackPanel>
                <Label
                    x:Name="HeadingContainer"
                    Content="{Binding Heading}"
                    FontSize="20"
                    Margin="0,0,0,8"  />
                <ContentPresenter
                    x:Name="ControlContainer"
                    Content="{Binding Control}"                 
                    />
            </StackPanel>
        </Border>
    </DockPanel>
</UserControl>

样本用法:

<Window x:Class="TkMVVMContainersSample.Services.TaskEditDialog.ItemEditView"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:Common="clr-namespace:TkMVVMContainersSample.Views.Common"
    Title="ItemEditView"
    >
    <Common:DialogControl>
        <Common:DialogControl.Heading>
            Edit item
        </Common:DialogControl.Heading>
        <Common:DialogControl.Control>
            <!-- Concrete dialog's content goes here -->
            <Grid>
                <Grid.RowDefinitions>
                    <RowDefinition Height="Auto" />
                    <RowDefinition Height="Auto" />
                </Grid.RowDefinitions>
                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="Auto" />
                    <ColumnDefinition Width="*" />
                </Grid.ColumnDefinitions>

                <Label Grid.Row="0" Grid.Column="0">Name</Label>
                <TextBox Grid.Row="0" Grid.Column="1" MinWidth="160" TabIndex="1" Text="{Binding Name}"></TextBox>
                <Label Grid.Row="1" Grid.Column="0">Phone</Label>
                <TextBox Grid.Row="1" Grid.Column="1" MinWidth="160" TabIndex="2" Text="{Binding Phone}"></TextBox>
            </Grid>
        </Common:DialogControl.Control>
        <Common:DialogControl.Buttons>
            <!-- Concrete dialog's buttons go here -->
            <Button Width="80" TabIndex="100" IsDefault="True" Command="{Binding OKCommand}">OK</Button>
            <Button Width="80" TabIndex="101" IsCancel="True" Command="{Binding CancelCommand}">Cancel</Button>
        </Common:DialogControl.Buttons>
    </Common:DialogControl>

</Window>

答案 2 :(得分:2)

如果您使用的是UserControl

我猜你真的想要:

<ContentPresenter Content="{Binding Buttons}"/>

这假定传递给控件的DataContext具有Buttons属性。

使用ControlTemplate

另一个选项是ControlTemplate,然后您可以使用:

<ContentPresenter ContentSource="Header"/>

你需要模仿一个实际上有'Header'的控件来执行此操作(通常是HeaderedContentControl)。