我使用MVVM动态构建了ContextMenu。问题是:MenuItems的内容全部在右侧==>太宽的ContextMenu。你有什么问题吗?感谢
以下是XAML中的代码:
<TreeView.ContextMenu>
<ContextMenu Name="RightClickMenu" ItemsSource="{Binding Path=SelectedItem.MenuItemsList}">
<ContextMenu.ItemTemplate >
<DataTemplate>
<!-- <MenuItem HorizontalAlignment="Left" Header="{Binding Name}" Command="{Binding Command}" -->
<StackPanel Orientation="Horizontal">
<Image Source="{Binding MyIcon}" Width="18" Height="18" SnapsToDevicePixels="True" />
<MenuItem Header="{Binding Name}" Command="{Binding Command}"
CommandParameter="{Binding RelativeSource={RelativeSource FindAncestor,
AncestorType={x:Type TreeView}}, Path=DataContext.SelectedItem}"
/>
</StackPanel>
</DataTemplate>
</ContextMenu.ItemTemplate>
</ContextMenu>
</TreeView.ContextMenu>
看起来像:
我希望ContextMenu是这样的:
第二个问题:
有时效果很好,但有时我会得到这些奇怪的东西。
------------------------------解决---------------- ----------------------------
对于Sac1。我通过添加x:Shared =&#34; False&#34;修改了您的解决方案。检查MSDN是否为x:Shared。
<Style TargetType="MenuItem" x:Shared="False">
<Setter Property="Icon">
<Setter.Value>
<Image Source="{Binding Path=MyIcon}" Height="20" Width="20" >
</Image>
</Setter.Value>
</Setter>
<Setter Property="Header" Value="{Binding Path=Name}" />
<Setter Property="Command" Value="{Binding Command}" />
<Setter Property="CommandParameter" Value="{Binding RelativeSource={RelativeSource FindAncestor,
AncestorType={x:Type TreeView}}, Path=DataContext.SelectedItem}" />
</Style>
对于菜单项的错误标题,我必须覆盖MenuItemViewModel中的方法ToString()。我不能理解为什么我必须覆盖ToString(),但它现在运作良好。
public class MenuItemViewModel : BindableBase
{
......
public string Name
{
get
{
return model.Name;
}
set
{
this.model.Name = value;
OnPropertyChanged("Name");
}
}
public override string ToString()
{
return Name;
}
....
}
答案 0 :(得分:0)
DataTemplate
不应使用ContextMenu
。只需使用它:
<ContextMenu>
<MenuItem Command="{Binding Path=Command}"
Icon="{Binding Path=MyIcon}"
Header="{Binding Path=Name}"
InputGetstureText="CTRL+O" />
</ContextMenu>
答案 1 :(得分:0)
DataTemplate
的{p> MenuItem
未按预期工作。
我使用了DataTemplate的Style insted:
<TreeView.Resources>
<Style TargetType="MenuItem">
<Setter Property="Icon" Value="{Binding MyIcon}" />
<Setter Property="Header" Value="{Binding Name}" />
<Setter Property="Command" Value="{Binding Command}" />
<Setter Property="CommandParameter" Value="{Binding RelativeSource={RelativeSource FindAncestor,
AncestorType={x:Type TreeView}}, Path=DataContext.SelectedItem}" />
</Style>
</TreeView.Resources>
<TreeView.ContextMenu>
<ContextMenu ItemsSource="{Binding Path=SelectedItem.MenuItemsList}" />
</TreeView.ContextMenu>
答案 2 :(得分:0)
不要在DataTemplate中使用MenuItem而是使用BorderThickness =&#34; 0&#34;背景=&#34;透明&#34;