或者你可以这样做......
您通常可以使用附加属性绑定来解决此问题
事件发送到Command-s - 然后直接发送到您的视图模型。
namespace YourNamespace // wrap that into e.g. 'xmlns:local="clr-namespace:YourNamespace"'
public static class Attach
{
public static ICommand GetAutoGenerateColumnEvent(DataGrid grid) { return (ICommand)grid.GetValue(AutoGenerateColumnEventProperty); }
public static void SetAutoGenerateColumnEvent(DataGrid grid, ICommand value) { grid.SetValue(AutoGenerateColumnEventProperty, value); }
public static readonly DependencyProperty AutoGenerateColumnEventProperty =
DependencyProperty.RegisterAttached("AutoGenerateColumnEvent", typeof(ICommand), typeof(Attach), new UIPropertyMetadata(null, OnAutoGenerateColumnEventChanged));
static void OnAutoGenerateColumnEventChanged(DependencyObject depObj, DependencyPropertyChangedEventArgs e)
{
DataGrid grid = depObj as DataGrid;
if (grid == null || e.NewValue is ICommand == false)
return;
ICommand command = (ICommand)e.NewValue;
grid.AutoGeneratingColumn += new EventHandler<DataGridAutoGeneratingColumnEventArgs>((s, args) => OnAutoGeneratingColumn(command, s, args));
// handle unsubscribe if needed
}
static void OnAutoGeneratingColumn(ICommand command, object sender, DataGridAutoGeneratingColumnEventArgs e)
{
if (command.CanExecute(e)) command.Execute(e);
}
}
在你的 XAML 中......
<DataGrid
local:Attach.AutoGenerateColumnEvent="{Binding AutoGeneratingColumnCommand}" AutoGenerateColumns="True" />
在你的视图模型中......
RelayCommand _autoGeneratingColumnCommand;
public RelayCommand AutoGeneratingColumnCommand
{
get
{
return _autoGeneratingColumnCommand ?? (_autoGeneratingColumnCommand = new RelayCommand(param =>
{
var e = param as DataGridAutoGeneratingColumnEventArgs;
if (e != null)
{
switch (e.PropertyName)
{
case "ID":
e.Cancel = true;
break;
default:
break;
}
}
},
param => true));
}
}
...RelayCommand : ICommand 的实现可以在网上找到(广泛使用)