将上下文菜单 header 绑定到 ListView 的选定项

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

我正在尝试将上下文菜单的 header 绑定到相应 ListView 的所选项目的 属性。 ItemsSource 的 objects 有一个 IsDuplicate 属性。知道哪里出了问题吗?

<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>

错误信息下方:

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')

ContextMenu 与关联的 ListView 不属于同一可视化树,因为它显示在不同的 window 中。因此,相对源和元素名称绑定不起作用。

相反,您可以使用 ContextMenuPlacementTarget,即 ListView

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