Tôi có một ListView hiển thị danh sách các giá trị chuỗi. Tôi muốn thêm mục nhập ngữ cảnh cho từng mục trong danh sách để xóa mục đã chọn. XAML của tôi trông giống như sau:menu ngữ cảnh để xóa các mục trong listview
<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>
Vấn đề là giá trị CommandParameter
luôn là rỗng. Tôi đã thêm một nút bổ sung để loại bỏ mục đã chọn để kiểm tra xem lệnh của tôi có hoạt động hay không. Nút có chính xác cùng một ràng buộc và loại bỏ các mục thông qua các nút hoạt động. Nút trông như thế này:
<Button Content="Remove selected item"
Command="{Binding RemoveItem}"
CommandParameter="{Binding ElementName=itemsListView, Path=SelectedItem}"/>
Lệnh trông như thế này:
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);
}
Bất cứ ý tưởng tại sao mục được chọn là null khi mở menu ngữ cảnh? Có lẽ một vấn đề tập trung của listview?
Có một cái nhìn trong cửa sổ Output của bạn, tôi đặt cược bạn sẽ tìm thấy một thông báo lỗi ràng buộc. Vì ContextMenu là một cửa sổ mới, tôi không chắc nó có thể truy cập itemsListView hay không. –
Có một cái nhìn xung quanh http://stackoverflow.com/questions/1013558/elementname-binding-from-menuitem-in-contextmenu và http://stackoverflow.com/questions/2617122/wpf-menuitem-command-binding-to -elementname-results-to-system-windows-data-error –