15

文字列値のリストを表示するListViewがあります。リスト内の各アイテムにコンテキストメニューエントリを追加して、選択したアイテムを削除したいと思います。私のXAMLは次のようになります。

<ListView x:Name="itemsListView" ItemsSource="{Binding MyItems}">
  <ListView.ContextMenu>
    <ContextMenu>
      <MenuItem Header="Remove"
                Command="{Binding RemoveItem}"
                CommandParameter="{Binding ElementName=itemsListView, Path=SelectedItem}" />
    </ContextMenu>
  </ListView.ContextMenu>
</ListView>

問題は、CommandParameter値が常にnullであるということです。コマンドが機能するかどうかを確認するために、選択したアイテムを削除するボタンを追加しました。ボタンにはまったく同じバインディングがあり、ボタンを介したアイテムの削除は機能します。ボタンは次のようになります。

<Button Content="Remove selected item"
        Command="{Binding RemoveItem}"
        CommandParameter="{Binding ElementName=itemsListView, Path=SelectedItem}"/>

コマンドは次のようになります。

private ICommand _removeItem;

public ICommand RemoveItem
{
  get { return _removeItem ?? (_removeItem = new RelayCommand(p => RemoveItemCommand((string)p))); }
}

private void RemoveItemCommand(string item)
{
  if(!string.IsNullOrEmpty(item))
    MyItems.Remove(item);  

}

コンテキストメニューを開いたときに選択した項目がnullになる理由はありますか?たぶんリストビューの焦点の問題?

4

3 に答える 3

40

H.B. is right. but you can also use RelativeSource Binding

    <ListView x:Name="itemsListView" ItemsSource="{Binding MyItems}">
        <ListView.ContextMenu>
            <ContextMenu>
                <MenuItem Header="Remove"
            Command="{Binding RemoveItem}"
            CommandParameter="{Binding RelativeSource={RelativeSource AncestorType=ContextMenu}, Path=PlacementTarget.SelectedItem}" />
            </ContextMenu>
        </ListView.ContextMenu>
    </ListView>
于 2012-06-18T12:11:25.930 に答える
4

ContextMenus are disconnected, you cannot use ElementName bindings. One workaround would be using Binding.Source and x:Reference which requires you to extract parts that use it to be in the resources (due to cyclical dependency errors). You can just put the whole context menu there.

An example:

<ListBox Name="lb" Height="200">
    <ListBox.Resources>
        <ContextMenu x:Key="cm">
            <MenuItem Header="{Binding ActualHeight, Source={x:Reference lb}}" />
        </ContextMenu>
    </ListBox.Resources>
    <ListBox.ContextMenu>
        <StaticResource ResourceKey="cm" />
    </ListBox.ContextMenu>
</ListBox>
于 2012-06-18T12:00:32.113 に答える
1

This work for me CommandParameter="{Binding}"

于 2016-12-15T17:02:35.300 に答える