将多个子项添加到自定义控件的属性

时间:2019-01-10 15:21:47

标签: c# wpf templates itemscontrol

我正在尝试创建一个基础视图,该基础视图知道在我的实际视图中放置一些我定义的按钮(动作)的位置。我有<h2>Status: { item.status ? 'OK' : 'Failed' }</h2> 派生自ViewABaseView是具有某些属性和通用模板的自定义控件。 BaseView源自ViewA,并定义了BaseView应该在BaseView中显示的一些按钮。

StackPanel的外观如下:

ViewA

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

<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>

我该如何完成?我试图使用<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> ,但不确定“ Actions”属性应为哪种类型,以及如何将其绑定到ItemsControl

1 个答案:

答案 0 :(得分:1)

我最终使用以下依赖项属性和模板中的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>

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