【发布时间】:2017-03-02 09:51:34
【问题描述】:
我想创建一个附加属性来保存 MenuItem 对象的集合。这些将在我的 GroupBoxes 的自定义 ControlTemplate 中使用。在那个 ControlTemplate 中,我想使用继承自 ItemsControl 的自定义 DropDownButton,并将 MenuItems 放在它的 Popup 中。
我在这个网站上找到了提示:
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>
到目前为止一切顺利。这一切都有效。我的问题是我找不到将 ControlTemplate 中的 MenuItems 集合用于 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 的任何提示?
【问题讨论】:
-
我从代码中看到的您的属性名称是“MenuItemsInternal”。据我所知,这不是用于 WPF 绑定目的的名称
-
@Jinish:哇,工作正常。我以为我已经尝试过了。
标签: c# wpf xaml data-binding attached-properties