首页 > 解决方案 > 将多个子项添加到自定义控件的属性

问题描述

我正在尝试创建一个基本视图,该视图知道在哪里放置我在实际视图中定义的一些按钮(操作)。我有ViewA它源自BaseView. BaseView是具有一些属性和通用模板的自定义控件。ViewA派生自BaseView并定义了一些BaseView应显示在StackPanel.

ViewA应该是这样的:

<BaseView x:Class="ViewA"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
             mc:Ignorable="d">
    <Grid>
        <!-- This will be the main content for the view -->
    </Grid>
    <BaseView.Actions>
        <!-- Here I want these buttons to be displayed in a StackPanel where the template is defined by BaseView -->
        <Button>Button1</Button>
        <Button>Button2</Button>
    </BaseView.Actions>
</BaseView>

这是我希望在其中显示按钮的 BaseView 模板:

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">

    <Style TargetType="{x:Type BaseView}">
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type BaseView}">
                    <Grid>
                        <Grid.RowDefinitions>
                            <RowDefinition Height="*"></RowDefinition>
                            <RowDefinition Height="Auto"></RowDefinition>
                        </Grid.RowDefinitions>
                        <ContentPresenter Grid.Row="0" />
                        <!-- I would like the buttons defined in Actions to display here in a StackPanel -->
                    </Grid>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>

</ResourceDictionary>

我怎样才能做到这一点?我试图使用 anItemsControl但我不确定“Actions”属性应该是什么类型以及如何将它绑定到一个ItemsControl

标签: c#wpftemplatesitemscontrol

解决方案


我最终在我的模板中使用以下依赖属性和 ItemsControl 来实现它:

public static readonly DependencyProperty ActionsProperty =
    DependencyProperty.Register("Actions", typeof(ObservableCollection<UIElement>), typeof(ModalWindow), new UIPropertyMetadata(new ObservableCollection<UIElement>()));

public ObservableCollection<UIElement> Actions
{
    get => (ObservableCollection<UIElement>)GetValue(ActionsProperty);
    set => SetValue(ActionsProperty, value);
}

<ItemsControl Grid.Row="1" ItemsSource="{TemplateBinding Actions}">
    <ItemsControl.ItemsPanel>
        <ItemsPanelTemplate>
            <StackPanel Orientation="Horizontal" HorizontalAlignment="Right" />
        </ItemsPanelTemplate>
    </ItemsControl.ItemsPanel>
</ItemsControl>

用法:

<BaseView.Actions>
    <Button>Action 1</Button>
    <Button>Action 2</Button>
</BaseView.Actions>

我认为 aUIElementCollection会更适合该属性的类型,但我不确定如何使用所需参数实例化该集合。


推荐阅读