2013-07-05 103 views
0

這個問題被廣泛討論,但我還沒有找到任何解決方案。在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> 
+0

什麼是'Commands'的數據類型?它是否具有DataTemplate中提到的兩個屬性'Title'和'Command'? – sthotakura

+0

另外,你在哪裏設置DataContext? – Killingsworth

+0

命令是我自己的類型,它具有這兩個字段。 DataContext在應用主題期間設置,它用於按鈕(我可以看到它加載ButtonTitle) –

回答

0

嘗試設置在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> 
+0

是的,我認爲這將有所幫助,但如何將此{綁定}附加到Button的DataContext?我已經嘗試了幾個變體,但他們並沒有幫助 –

+0

不確定是否明白你的意思......你不知道綁定是如何工作的?或者你不能將它附加到你的userControl/Window?或只是按鈕? '