数据网格上下文菜单仅用于单个选择
本文关键字:用于 单个 选择 菜单 数据网 网格 上下文 数据 | 更新日期: 2023-09-27 18:12:20
我有一个带有上下文菜单的数据网格。如何防止上下文菜单显示多个选择?我试图添加附加属性,但得到一个错误附加属性'ContextMenuVisibilityMode'在类型' processintasnceactitiesview '中未找到
namespace TiM.Windows.App.View
{
public partial class ProcessIntasnceActivitiesView
{
public static readonly DependencyProperty ContextMenuVisibilityModeProperty =
DependencyProperty.RegisterAttached("ContextMenuVisibilityMode", typeof (string),
typeof (ProcessIntasnceActivitiesView),
new PropertyMetadata("Multiple", OnContextMenuVisibilityModeChanged));
private static void OnContextMenuVisibilityModeChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var dgrd = d as DataGrid;
if (dgrd != null)
dgrd.ContextMenuOpening += (sender, args) =>
{
switch (e.NewValue.ToString())
{
case "Single":
args.Handled = (sender as DataGrid)?.SelectedItems.Count > 1;
break;
case "Multiple":
args.Handled = !((sender as DataGrid)?.SelectedItems.Count > 1);
break;
}
};
}
...
}
xmlns:local="clr-namespace:TiM.Windows.App.View"
<DataGrid ... local:ProcessIntasnceActivitiesView.ContextMenuVisibilityMode="Single">
处理DataGrid
的ContextMenuOpening
事件
private void DataGrid_ContextMenuOpening_1(object sender, ContextMenuEventArgs e)
{
e.Handled = (sender as DataGrid).SelectedItems.Count > 1;
}
您可以将此逻辑放入AttachedProperty
中。
namespace WpfStackOverflow
{
/// <summary>
/// Interaction logic for Window2.xaml
/// </summary>
public partial class Window2 : Window
{
...
// Using a DependencyProperty as the backing store for ContextMenuVisibilityMode. This enables animation, styling, binding, etc...
public static readonly DependencyProperty ContextMenuVisibilityModeProperty =
DependencyProperty.RegisterAttached("ContextMenuVisibilityMode", typeof(string), typeof(Window2), new PropertyMetadata("Extended", new PropertyChangedCallback(OnContextMenuVisibilityModeChanged)));
private static void OnContextMenuVisibilityModeChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
DataGrid dgrd = d as DataGrid;
dgrd.ContextMenuOpening += ((sender, args) => {
if (e.NewValue.ToString() == "Single")
args.Handled = (sender as DataGrid).SelectedItems.Count > 1;
else if (e.NewValue.ToString() == "Extended")
args.Handled = !((sender as DataGrid).SelectedItems.Count > 1);
else {
// do something
}
});
}
...
}
并应用于DataGrid
:
<Window ...
xmlns:local="clr-namespace:WpfStackOverflow"
...>
<DataGrid local:Window2.ContextMenuVisibilityMode="Single" ... />