2009-06-20 81 views
7

我有一個用戶控件,其中包含一個來自ObservableCollection的簡單項目的ListView。我希望ListView的ContextMenu根據ListView中選擇的內容來包含項目。如果沒有選擇項目,一些MenuItems不應該是可見的。綁定ContextMenu的MenuItem對ListView選擇的可見性

我打開ContextMenu時甚至不會調用我的轉換器。的結合似乎是錯的,我覺得這在輸出窗口:

System.Windows.Data Error: 4 : Cannot find source for binding with reference 'ElementName=listView'. BindingExpression:Path=SelectedItem; DataItem=null; target element is 'MenuItem' (Name=''); target property is 'Visibility' (type 'Visibility')

我不明白什麼是錯的,不能在網上搜索看着辦吧。

下面是一些簡單的代碼:

<UserControl x:Class="MyApp.DatabaseControl" 
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
xmlns:l="clr-namespace:MyApp" 
Height="Auto" 
Width="Auto"> 

<UserControl.Resources> 
    <l:ValueToVisibilityConverter x:Key="valueToVisibility" /> 
</UserControl.Resources> 

<Grid> 
    <ListView x:Name="listView" ItemsSource="{Binding Persons}"> 
     <ListView.View> 
      <GridView> 
       <GridViewColumn Width="140" Header="First Name" DisplayMemberBinding="{Binding FirstName}"/> 
       <GridViewColumn Width="140" Header="Last Name" DisplayMemberBinding="{Binding LastName}" /> 
      </GridView> 
     </ListView.View> 

     <ListView.ContextMenu> 
      <ContextMenu> 
       <MenuItem 
        Header="Open" 
        Visibility="{Binding SelectedItem, ElementName=listView, Converter={StaticResource valueToVisibility}}"/> 
       <Separator/> 
       <MenuItem Header="Add..."/> 
       <MenuItem Header="Remove"/> 
      </ContextMenu> 
     </ListView.ContextMenu> 
    </ListView> 
</Grid> 

非常感謝!

回答

7

問題是ContextMenuListBox不在同一視覺樹中,因此綁定找不到ListBox。如果你對PlacementTarget進行綁定,那應該可以做到這一點:

<MenuItem Header="Open" 
    Visibility="{Binding RelativeSource={RelativeSource FindAncestor, 
     AncestorType=ContextMenu}, Path=PlacementTarget.SelectedItem, 
     Converter={StaticResource valueToVisibility}}" /> 
+0

謝謝,這個伎倆! – fury 2009-06-21 03:20:13