Я хочу создать присоединенное свойство для хранения коллекции объектов MenuItem. Они должны использоваться в моем пользовательском шаблоне ControlTemplate для групповых ящиков. В этом ControlTemplate я хочу использовать свой пользовательский DropDownButton, который наследуется от ItemsControl и будет помещать MenuItems внутрь своего всплывающего окна.
Я нашел подсказки на этом сайте:
https://siderite.dev/blog/collection-attached-properties-with.html
Вот что у меня есть:
Прикрепленное свойство:
public class General {
public static readonly DependencyProperty MenuItemsProperty =
DependencyProperty.RegisterAttached(
"MenuItemsInternal",from convention
typeof(ObservableCollection<MenuItem>),
typeof(General),
new PropertyMetadata(default(ObservableCollection<MenuItem>)));
public static ObservableCollection<MenuItem> GetMenuItems(UIElement element)
{
var collection = (ObservableCollection<MenuItem>) element.GetValue(MenuItemsProperty);
if (collection == null)
{
collection = new ObservableCollection<MenuItem>();
element.SetValue(MenuItemsProperty, collection);
}
return collection;
}
public static void SetMenuItems(UIElement element, ObservableCollection<MenuItem> value)
{
element?.SetValue(MenuItemsProperty, value);
}
}
Использование прикрепленного свойства:
...
<GroupBox Style="{StaticResource Style.GroupBox.EditableSubSection}">
<ap:General.MenuItems>
<MenuItem Header="Aktion abc" />
<MenuItem Header="Aktion xyz" />
</ap:General.MenuItems>
</GroupBox>
Все идет нормально. Это все работает. Моя проблема в том, что я не могу найти способ использовать коллекцию MenuItems в моем ControlTemplate для GroupBox.
<Style x:Key="Style.GroupBox.EditableSubSection"
TargetType="{x:Type GroupBox}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type GroupBox}">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<TextBlock Text="{TemplateBinding Header}" />
<Separator Grid.Row="1" />
<ContentPresenter Grid.Row="2" />
<Grid Grid.Row="0" HorizontalAlignment="Right">
...
<controls:DropDownButton Width="{Binding ActualHeight,
RelativeSource={RelativeSource Self}}"
ItemsSource="{Binding Path=(ap:General.MenuItems),
RelativeSource={RelativeSource TemplatedParent}}" />
</Grid>
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
При запуске это проблема, похоже, связана с привязкой
ItemsSource="{Binding Path=(ap:General.MenuItems), RelativeSource={RelativeSource TemplatedParent}}"
Я получаю исключение со следующим сообщением:
InvalidOperationException: Property path is not valid. 'General' does not have a public property named 'MenuItems'
Кто-нибудь сталкивался с этим раньше или какие-либо советы о том, как привязать к AttachedProperty с нестандартным именем?