【发布时间】:2020-11-03 21:42:15
【问题描述】:
由于某种原因,即使我只指定了 1 个菜单项,当我重用我的用户控件时也会出现重复的上下文菜单项。
例如,测试 1 和测试 2 菜单项出现在两个用户控件中,即使它们是在单独的用户控件中编码的。
我的主窗口看起来像
<Grid>
<Grid.RowDefinitions>
<RowDefinition />
<RowDefinition />
</Grid.RowDefinitions>
<local:OptionsMenu Grid.Row="0" MenuWidth="23" MenuHeight="7">
<local:OptionsMenu.MenuItems>
<MenuItem Header="Test 1"/>
</local:OptionsMenu.MenuItems>
</local:OptionsMenu>
<local:OptionsMenu Grid.Row="1" MenuWidth="23" MenuHeight="7">
<local:OptionsMenu.MenuItems>
<MenuItem Header="Test 2"/>
</local:OptionsMenu.MenuItems>
</local:OptionsMenu>
</Grid>
</Window>
我的用户控件看起来像
<UserControl.Resources>
<Style TargetType="{x:Type Button}" x:Key="MenuButton">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type Button}">
<Canvas>
<Path Data="M12.5,6.5 C12.5,9.8137085 9.8137085,12.5 6.5,12.5 C3.1862915,12.5 0.5,9.8137085 0.5,6.5 C0.5,3.1862915 3.1862915,0.5 6.5,0.5 C9.8137085,0.5 12.5,3.1862915 12.5,6.5 z M30.5,6.5 C30.5,9.8137085 27.813708,12.5 24.5,12.5 C21.186292,12.5 18.5,9.8137085 18.5,6.5 C18.5,3.1862915 21.186292,0.5 24.5,0.5 C27.813708,0.5 30.5,3.1862915 30.5,6.5 z M48.5,6.5 C48.5,9.8137085 45.813708,12.5 42.5,12.5 C39.186292,12.5 36.5,9.8137085 36.5,6.5 C36.5,3.1862915 39.186292,0.5 42.5,0.5 C45.813708,0.5 48.5,3.1862915 48.5,6.5 z"
Fill="Black"
HorizontalAlignment="Left"
Stretch="Fill"
Stroke="Black"
VerticalAlignment="Top"
Height="{Binding MenuHeight}"
Width="{Binding MenuWidth}" />
<ItemsPresenter />
</Canvas>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</UserControl.Resources>
<Grid>
<Button x:Name="Root" Style="{DynamicResource MenuButton}" Click="Button_Click">
<Button.ContextMenu >
<ContextMenu ItemsSource="{Binding MenuItems}" />
</Button.ContextMenu>
</Button>
</Grid>
</UserControl>
背后的代码
public ObservableCollection<DependencyObject> MenuItems
{
get { return (ObservableCollection<DependencyObject>)GetValue(MenuItemsProperty); }
set { SetValue(MenuItemsProperty, value); }
}
internal static readonly DependencyProperty MenuItemsProperty = DependencyProperty.Register(
"MenuItems", typeof(ObservableCollection<DependencyObject>), typeof(OptionsMenu),
new FrameworkPropertyMetadata(new ObservableCollection<DependencyObject>()));
【问题讨论】:
-
你能向我们展示整个 XAML 吗?
-
我已经更新了我的 XAML
-
除了答案中解释的内容外,尚不清楚为什么您认为需要使用 ObservableCollection 作为属性类型。普通的
List<DependencyObject>也可以。