WPF 数据网格的"生成列"在使用事件触发器时不触发



我正在尝试在一个简单的级别上测试它,我有以下任务数据网格视图.xaml:

<UserControl x:Class="Example.Views.TasksDatagridView" ...>
<UserControl.Resources>
<local:CompleteConverter x:Key="completeConverter" />
<local:Tasks x:Key="tasks" />
<CollectionViewSource x:Key="cvsTasks" Source="{Binding Path=tasks}">
<CollectionViewSource.GroupDescriptions>
<PropertyGroupDescription PropertyName="ProjectName"/>
</CollectionViewSource.GroupDescriptions>
</CollectionViewSource>
</UserControl.Resources>
<Grid>
<DataGrid x:Name="myDG" AutoGenerateColumns="True" ItemsSource="{Binding Source={StaticResource cvsTasks}}">
<i:Interaction.Triggers>
<i:EventTrigger EventName="AutoGeneratingColumn">
<i:InvokeCommandAction Command="{Binding GenColumns}" />
</i:EventTrigger>
</i:Interaction.Triggers>
</DataGrid>
</Grid>
</UserControl>

在我的 TasksDatagridView.xaml 中.cs我尝试先设置数据上下文this.DataContext = new ViewModels.TaskDgVm()然后InitializeComponent(),反之亦然。

在我的主窗口 MainWindow.xaml 中,我像这样引用控件:

<Window x:Name="MainWindow" x:Class="Example.Views.MyMainWindowView" ...>
<Grid>
<local:TasksDatagridView x:Name="tview" />
</Grid>
</Window>

这是一个派生的例子,表明了这一点,所以请原谅拼写错误。所以我有两个问题:

  1. 在我引用控件的 MainWindow.xaml 行中:<local:TasksDatagridView x:Name="tview" />它说它抛出了一个 system.exception,但代码仍然可以编译并运行良好。

  2. 未触发自动生成列。

真的,我试图弄清楚#2以及为什么这个特定事件没有触发。现在我在执行方法中有一个简单的打印,当将事件名称替换为数据网格的简单单击或加载事件时,该命令工作正常,几乎任何其他事件都会被触发,这告诉我它不在我的视图模型或委托命令类中。关于为什么自动生成列事件不使用命令的任何想法?注意 我已确保事件名称没有拼写错误。

编辑: 发布问题后,我在这里发现了一个相关问题:MVVM - WPF 数据网格 - 自动生成列事件 但是,他们使用mvvm-light工具包,而我正在使用表达式混合交互性库。虽然同样的答案可能适用于这两个问题,但它们确实是两个独立的工具包。

所以基于这个线程 MVVM - WPF 数据网格 - 自动生成列事件 我相信在其中一些事件中没有构建可视化树。

但是,提供了一种替代方案,可以解决问题,同时避免代码落后:

public class AutoGeneratingColumnEventToCommandBehaviour
{
public static readonly DependencyProperty CommandProperty =
DependencyProperty.RegisterAttached(
"Command", 
typeof(ICommand), 
typeof(AutoGeneratingColumnEventToCommandBehaviour),
new PropertyMetadata(
null,
CommandPropertyChanged));
public static void SetCommand(DependencyObject o, ICommand value)
{
o.SetValue(CommandProperty, value);
}
public static ICommand GetCommand(DependencyObject o)
{
return o.GetValue(CommandProperty) as ICommand;
}
private static void CommandPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var dataGrid = d as DataGrid;
if (dataGrid != null)
{
if (e.OldValue != null)
{
dataGrid.AutoGeneratingColumn -= OnAutoGeneratingColumn;
}
if (e.NewValue != null)
{
dataGrid.AutoGeneratingColumn += OnAutoGeneratingColumn;
}
}
}
private static void OnAutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e)
{
var dependencyObject = sender as DependencyObject;
if (dependencyObject != null)
{
var command = dependencyObject.GetValue(CommandProperty) as ICommand;
if (command != null && command.CanExecute(e))
{
command.Execute(e);
}
}
}
}

最新更新