当我尝试编译以下WPF DataGrid代码时,Visual Studio会抱怨“'MenuItem_Click'无效。'Click'不是'System.Windows.Controls.DataGridTextColumn'上的事件。”
<DataGrid x:Name="myDataGrid" ItemsSource="{Binding myItems}" AutoGenerateColumns="False">
<DataGrid.ColumnHeaderStyle>
<Style TargetType="{x:Type DataGridColumnHeader}">
<Setter Property="ContextMenu">
<Setter.Value>
<ContextMenu>
<MenuItem Header="Header Text" Click="MenuItem_Click"/>
</ContextMenu>
</Setter.Value>
</Setter>
</Style>
</DataGrid.ColumnHeaderStyle>
<DataGrid.Columns>
<DataGridTextColumn Header="c1" Binding="{Binding C1}" />
<DataGridTextColumn Header="c2" Binding="{Binding C2}" />
<DataGridTextColumn Header="c3" Binding="{Binding C2}" />
</DataGrid.Columns>
</DataGrid>
Click处理程序在MenuItem上定义,而不是在DataGridTextColumn上定义。为什么让这个Click处理程序破坏DataGrid?
答案 0 :(得分:7)
XAML找不到MenuItem_Click
,因为<Style>
会创建一个新的XAML名称范围(有关名称范围的说明,请参阅WPF XAML Namescopes)。 XAML仅在封闭的名称范围内查找事件处理程序名称。
要解决此问题,请将ContextMenu
移至资源,如下所示:
<DataGrid x:Name="myDataGrid" ItemsSource="{Binding myItems}" AutoGenerateColumns="False">
<DataGrid.Resources>
<ContextMenu x:Key="myContextMenu">
<MenuItem Header="Header Text" Click="MenuItem_Click"/>
</ContextMenu>
</DataGrid.Resources>
<DataGrid.ColumnHeaderStyle>
<Style TargetType="{x:Type DataGridColumnHeader}">
<Setter Property="ContextMenu" Value="{StaticResource myContextMenu}"/>
</Style>
</DataGrid.ColumnHeaderStyle>
<DataGrid.Columns>
<DataGridTextColumn Header="c1" Binding="{Binding C1}" />
<DataGridTextColumn Header="c2" Binding="{Binding C2}" />
<DataGridTextColumn Header="c3" Binding="{Binding C2}" />
</DataGrid.Columns>
</DataGrid>