這個問題被廣泛討論,但我還沒有找到任何解決方案。在WPF中生成上下文菜單
我根據數據模板生成(在MyObject.Theme.xaml中)一個項目。它必須是一個帶有標題的按鈕。當我點擊這個按鈕時,它必須顯示看到根據集合生成的菜單。
但我看到的只是一個空的上下文菜單。它看起來像沒有看到Button的DataContext,我找不到,如何將它傳遞給ContextMenu。
的代碼如下:
<DataTemplate DataType="{x:Type fields:ButtonWithMenu}">
<Button Grid.Column="1" Content="{Binding Path=ButtonTitle}">
<!--- Show ContextMenu on left mouse clik)
<Button.Style>
<Style TargetType="{x:Type Button}">
<Style.Triggers>
<EventTrigger RoutedEvent="Click">
<EventTrigger.Actions>
<BeginStoryboard>
<Storyboard>
<BooleanAnimationUsingKeyFrames Storyboard.TargetProperty="ContextMenu.IsOpen">
<DiscreteBooleanKeyFrame KeyTime="0:0:0" Value="True"/>
</BooleanAnimationUsingKeyFrames>
</Storyboard>
</BeginStoryboard>
</EventTrigger.Actions>
</EventTrigger>
</Style.Triggers>
</Style>
</Button.Style>
<!--- Try to load items from Button.DataContext.Commands -->
<Button.ContextMenu>
<ContextMenu ItemsSource="{Binding Path=Commands}">
<ContextMenu.ItemTemplate>
<DataTemplate>
<MenuItem Header="{Binding Path=Title}" Command="{Binding Path=Command}" />
</DataTemplate>
</ContextMenu.ItemTemplate>
</ContextMenu>
</Button.ContextMenu>
</Button>
</DataTemplate>
什麼是'Commands'的數據類型?它是否具有DataTemplate中提到的兩個屬性'Title'和'Command'? – sthotakura
另外,你在哪裏設置DataContext? – Killingsworth
命令是我自己的類型,它具有這兩個字段。 DataContext在應用主題期間設置,它用於按鈕(我可以看到它加載ButtonTitle) –