Добавление нескольких дочерних элементов в свойство пользовательского элемента управления - PullRequest
0 голосов
/ 10 января 2019

Я пытаюсь создать базовый вид, который знает, где разместить некоторые кнопки (действия), которые я определяю в своих реальных представлениях. У меня есть 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>

Как я могу это сделать? Я пытался использовать ItemsControl, но я не уверен, какой тип должен иметь свойство "Actions" и как его привязать к ItemsControl?

1 Ответ

0 голосов
/ 14 января 2019

В итоге я реализовал это с помощью приведенного ниже свойства зависимостей и 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 было бы лучше подходит для типа свойства, но я не уверен, как создать экземпляр этой коллекции с необходимыми параметрами.

...