c# - 将多个子项添加到自定义控件的属性
问题描述
我正在尝试创建一个基本视图,该视图知道在哪里放置我在实际视图中定义的一些按钮(操作)。我有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
?
解决方案
我最终在我的模板中使用以下依赖属性和 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
会更适合该属性的类型,但我不确定如何使用所需参数实例化该集合。
推荐阅读
- sqlite - react-native-sqlite-storage 如何打开指定目录的文件?
- scala - 为什么 UDF 在流式查询中抛出 NotSerializableException?
- amazon-web-services - 如何编写用于在 AWS 中创建 API 网关的 shell 脚本
- java - 基于正文内容的 Apache Camel 自定义重新排序
- javascript - 将 Javascript 变量设置为 PHP 变量
- android - 在哪里做 Arrow.io IO.runUnsafeSync() ?ViewModel 还是 Activity/Fragment?
- objective-c - glreadpixels 在不同的屏幕上返回错误的值
- php - 如何设置多个值来分配会话
- html - 使用单独的 id HTML
- c - 如何在不影响 C 中其他元素索引的情况下删除结构数组?