2009-09-09 71 views
6

我想實現以下目標:如何設置綁定項目的ContextMenu?

<Style TargetType="ListBoxItem"> 
    <Setter Property="ContextMenu"> 
     <Setter.Value> 
      <ContextMenu> 
       <MenuItem Name="mnuEdit" Header="_Edit" Click="MenuItem_Click" /> 
      </ContextMenu> 
     </Setter.Value> 
    </Setter> 
<Style> 

但它拋出以下異常:

Cannot add content of type 'System.Windows.Controls.ContextMenu' 
to an object of type 'System.Object'. 
Error at object 'System.Windows.Controls.ContextMenu' 
in markup file blah blah blah 

回答

5

試試這個:

<ContextMenu x:Key="contextMenu"> 
    <MenuItem Name="mnuEdit" Header="_Edit" Click="MenuItem_Click" /> 
</ContextMenu> 

<Style TargetType="ListBoxItem"> 
    <Setter Property="ContextMenu" Value="{DynamicResource contextMenu}" /> 
</Style> 
+0

不錯,但爲什麼呢?其他屬性可以在不使用靜態或動態資源的情況下進行設置。 – jrwren 2011-05-11 20:16:42

+1

@jrwren,好點。我的_guess_是,如果按照它在問題中顯示的方式進行操作,則會爲每個菜單項創建一個上下文菜單,當您只需要一個菜單​​項時這可能會浪費。我知道這不是一個確鑿的解釋。 – 2011-05-12 07:30:04

+1

我很想有一個具體的答案。知道爲什麼肯定會幫助我理解WPF。 – jrwren 2011-05-12 14:38:45

相關問題