2017-10-11 167 views
-1

我想在WPF DataGrid中创建一个动态的上下文菜单。以下是我需要帮助的问题:C#WPF上下文菜单数据绑定

1)当子菜单正常工作时,根菜单项标题不与ViewModel绑定。

2)子菜单总是弹出在左侧而不是右侧。我怎样才能解决这个风格?

<DataGrid.ContextMenu> 
<ContextMenu ItemsSource="{Binding PackageCM.Members}" HasDropShadow="True" Placement="Right"> 
    <ContextMenu.ItemContainerStyle> 
     <Style TargetType="MenuItem"> 
      <Setter Property="Header" Value="{Binding CategoryName}" /> 
     </Style> 
    </ContextMenu.ItemContainerStyle> 
    <ContextMenu.ItemTemplate> 
     <HierarchicalDataTemplate ItemsSource="{Binding Items}"> 
      <MenuItem Header="{Binding DisplayName}" Command="{Binding AllPackagesVM.OpenCOBAPackageCommand, Source={StaticResource Locator}}"></MenuItem> 
     </HierarchicalDataTemplate> 
    </ContextMenu.ItemTemplate> 
</ContextMenu> 

Root Menu Item Header are not being bind.

基本上,上下文菜单被结合PackageCM.Members与具有类别对象的列表,我想显示在上下文菜单根类别名称。接下来,每个类别都包含一个项目列表,这些项目将显示为子菜单。

在此先感谢您的帮助。

回答

1

首先,您的ContextMenu.ItemTemplate定义不正确,当您为ContextMenu设置ItemSource时,您并未自己定义MenuItem,因为实际上ContextMenu会将此内容包装到另一个MenuItem中。所以,你需要你的模板改变这样的事情:

<ContextMenu ItemsSource="{Binding PackageCM.Members}" ...> 
    <ContextMenu.ItemTemplate> 
     <HierarchicalDataTemplate ItemsSource="{Binding Items}"> 
      <TextBlock Text="{Binding DisplayName}"></TextBlock > 
     </HierarchicalDataTemplate> 
    </ContextMenu.ItemTemplate> 
</ContextMenu> 

你需要把一个TextBlock而不是MenuItem因为你想在你ContextMenu菜单来显示文本,并在模型的Text属性绑定到一个欢迎使用属性。但是为了这样工作,用于子菜单的根菜单和模型的模型必须具有一个名称相同的属性,对于子菜单,您的情况为DisplayName,因此在根菜单模型中也必须具有一个名为DisplayName,此属性绑定到TextBlock的Text属性。

您需要在模型中进行一些重命名,或者在Category模型中引入一个名为DisplayName的新名称。所以你的模型会有一个共同的问题,像这样的代码片段:

// for root menu 
public class Category 
{ 
    public string CategoryName { get; } 
    public string DisplayName => CategoryName; 
    ... 
} 

// for submenus 
public class Item 
{ 
    public string DisplayName { get; } 
    ... 
} 

希望这个解释有助于你理解丢失标题值的问题。

+0

非常感谢你,Redouane。它运行良好,现在我可以看到ContextMenu正确显示。此外,现在我明白了ContextMenu是如何与子菜单一起工作的。 –