[英]Adding multiple children to a property of a custom control
我正在尝试创建一个基础视图,该基础视图知道在我的实际视图中定义的一些按钮(动作)的放置位置。 我有从BaseView
派生的ViewA
。 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
?
我最终使用以下依赖项属性和模板中的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
会更适合于属性的类型,但是我不确定如何用所需的参数实例化该集合。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.