如何为ListBoxItems创建动态上下文菜单?

时间:2016-09-28 15:12:08

标签: wpf wpf-style

我的风格似乎不起作用。尽管Snoop告诉我DataContext的{​​{1}}是正确的,但没有任何内容显示出来。如果ListBoxItem的绑定出现问题,我希望看到一个空的上下文菜单。

风格:

Commands

snoop DataContext:

document here from elastic search

甚至没有设置显示ContextMenu属性的snoop属性。

SnoopDataContext

这里的想法是,在不知道任何类型的情况下,我可以有一个列表框项样式,如果它绑定的东西有一个名为HasCommands的属性,并且它被设置为true,那么它将设置一个上下文该列表框项目上的菜单,绑定到Commands属性。

我没有收到来自<ContextMenu x:Key="CommandsContextMenu" ItemsSource="{Binding Commands}"> <Style TargetType="MenuItem"> <Setter Property="Header" Value="{Binding Name}"/> </Style> </ContextMenu> <Style TargetType="ListBoxItem"> <Setter Property="ContextMenu" Value="{StaticResource CommandsContextMenu}" /> <Style.Triggers> <DataTrigger Value="True"> <DataTrigger.Binding> <Binding Path="DataContext.HasCommands" /> </DataTrigger.Binding> </DataTrigger> </Style.Triggers> </Style>

的任何绑定错误或警告

为什么不设置上下文菜单?

1 个答案:

答案 0 :(得分:0)

事实证明,问题是使用了从ListBox

继承的东西

以供参考,我的定义类:

// adapted from http://stackoverflow.com/questions/3350187/wpf-c-rearrange-items-in-listbox-via-drag-and-drop
// which was probably adapted from http://wpftutorial.net/DragAndDrop.html
type DragDropListBox() as self =
    inherit ListBox()

从那里只挂钩以下

  • self.PreviewMouseLeftButtonUp
  • self.PreviewMouseMove
  • 覆盖x.OnItemsSourceChanged

并且在初始化中将覆盖ItemContainerStyle ,如下所示:

事实证明,问题是使用了从ListBox

继承的东西

供参考,这是我班上的佼佼者:

// adapted from http://stackoverflow.com/questions/3350187/wpf-c-rearrange-items-in-listbox-via-drag-and-drop
// which was probably adapted from http://wpftutorial.net/DragAndDrop.html
type DragDropListBox() as self =
    inherit ListBox()

从那里只挂钩以下

  • self.PreviewMouseLeftButtonUp
  • self.PreviewMouseMove
  • 覆盖x.OnItemsSourceChanged

并且在初始化中将覆盖ItemContainerStyle ,如下所示:

do
    self.PreviewMouseLeftButtonUp.Add listBoxPreviewMouseLeftButtonUp
    //self.PreviewMouseLeftButtonDown.Add listBoxPreviewMouseMove //.AddHandler (MouseButtonEventHandler previewMouseMove)
    self.PreviewMouseMove.Add listBoxPreviewMouseMove
    let style =
        let s = Style(typeof<ListBoxItem>)
        s.Setters.Add (Setter(ListBoxItem.AllowDropProperty, true))
        s.Setters.Add (EventSetter(ListBoxItem.PreviewMouseLeftButtonDownEvent, MouseButtonEventHandler listBoxPreviewMouseLeftButtonDown))
        s.Setters.Add (EventSetter(ListBoxItem.DropEvent, DragEventHandler listBoxItemDrop))

        s
    self.ItemContainerStyle <- style

现在我必须弄清楚你是否可以一起添加两种风格。