Bạn đã có một menu ngữ cảnh với đánh dấu của bạn.
Nếu bạn muốn thực hiện một số thao tác, một trong những cách là kiểm tra xem mục nào đã được nhấp vào trong chức năng Click của menu. Ví dụ, bạn có ListBox tiếp theo:
<ListBox Name="someListBox">
<ListBox.ContextMenu>
<ContextMenu>
<MenuItem Header="Delete" Click="MenuItemDelete_Click"/>
</ContextMenu>
</ListBox.ContextMenu>
<ListBoxItem>...</ListBoxItem>
<ListBoxItem>...</ListBoxItem>
<ListBoxItem>...</ListBoxItem>
</ListBox>
Và chức năng có thể tiếp theo:
private void MenuItemDelete_Click(object sender, RoutedEventArgs e)
{
if (someListBox.SelectedIndex == -1) return;
// Hypothetical function GetElement retrieves some element
var element = GetElement(someListBox.SelectedIndex);
// Hypothetical function DeleteElement
DeleteElement(element);
}
Cập nhật 05 tháng 3 2012:
Dưới đây là một biến thể của listbox của bạn. Bạn có thể thêm một menu ngữ cảnh không vào hộp danh sách nhưng vào các mục danh sách. Ví dụ:
<ListBox Name="someListBox" MouseDown="someListBox_MouseDown">
<ListBox.Resources>
<!--Defines a context menu-->
<ContextMenu x:Key="MyElementMenu">
<MenuItem Header="Delete" Click="MenuItemDelete_Click"/>
</ContextMenu>
<!--Sets a context menu for each ListBoxItem in the current ListBox-->
<Style TargetType="{x:Type ListBoxItem}">
<Setter Property="ContextMenu" Value="{StaticResource MyElementMenu}"/>
</Style>
</ListBox.Resources>
<ListBoxItem>...</ListBoxItem>
<ListBoxItem>...</ListBoxItem>
<ListBoxItem>...</ListBoxItem>
</ListBox>
1) Chức năng này sẽ unsellect tất cả các mục khi bạn nhấp vào không gian trống trong ListBox:
private void someListBox_MouseDown(object sender, MouseButtonEventArgs e)
{
someListBox.UnselectAll();
}
2) Khi bạn nhấp vào mục lisboxt, nó là màu xanh. Khi bạn nhấp chuột phải vào mục hộp danh sách, nó vẫn là màu xanh, nhưng nếu một menu ngữ cảnh xuất hiện, mục hộp danh sách sẽ trở thành màu xám, có thể nó là như vậy vì mục này mất tiêu điểm.
3) Xóa chức năng hoạt động tốt:
private void MenuItemDelete_Click(object sender, RoutedEventArgs e)
{
if (someListBox.SelectedIndex == -1)
{
return;
}
someListBox.Items.RemoveAt(someListBox.SelectedIndex);
}
cảm ơn, tôi sẽ cố gắng này vào buổi tối và cập nhật. – user979033
OK cảm ơn, bây giờ làm thế nào tôi có thể "bắt" tên tập tin (đường dẫn) tôi nhấp vào? – user979033
tôi muốn thêm 3 chức năng trong menu (mỗi tùy chọn trong menu sẽ có chức năng khác nhau) nên vẫn cần kiểm tra xem mục nào đã được nhấp? và tôi không hiểu 2 dòng cuối cùng trong hàm của MenuItemDelete_Click – user979033