簡體   English   中英

在WPF中生成上下文菜單

[英]Generate context menu in 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>

嘗試設置DataContext…

<Button>
    <Button.ContextMenu >
        <ContextMenu DataContext="{Binding}" ItemsSource="{Binding Path=Commands}">
            <ContextMenu.ItemTemplate>
                <DataTemplate>
                    <MenuItem Header="{Binding Path=Title}" Command="{Binding Path=Command}" />
                </DataTemplate>
            </ContextMenu.ItemTemplate>
        </ContextMenu>
    </Button.ContextMenu>
</Button>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM