Norbert
Norbert

Reputation: 35

Binding a context menu header to the selected item of a ListView

I am trying to bind the header of the context menu to a property of the selected item of the respective ListView. The objects of the ItemsSource have an IsDuplicate property. Any idea what is wrong?

<ListView x:Name="AthletesListView" ItemsSource="{Binding FoundAthletes}">
   <ListView.ContextMenu>
      <ContextMenu>
         <MenuItem Name="AddorEditAthleteMenuItem" 
                   Header="{Binding SelectedItem.IsDuplicate, 
                          ElementName=AthletesListView,
                          Converter={StaticResource FoundAthletesAddEditMenuItemConverter}}" 
                   Click="AddAthleteMenuItem_Click"/>
      </ContextMenu>
   </ListView.ContextMenu>

Below the error message:

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

Upvotes: 0

Views: 320

Answers (1)

thatguy
thatguy

Reputation: 22089

The ContextMenu is not part of the same visual tree as the associated ListView, because it is displayed in a different window. Consequently, relative source and element name bindings don't work.

Instead, you can use the PlacementTarget of the ContextMenu, which is the ListView.

<MenuItem Name="AddorEditAthleteMenuItem" 
          Header="{Binding PlacementTarget.SelectedItem.IsDuplicate, RelativeSource={RelativeSource AncestorType={x:Type ContextMenu}}, Converter={StaticResource FoundAthletesAddEditMenuItemConverter}}"
          Click="AddAthleteMenuItem_Click"/>

Upvotes: 0

Related Questions