我有一个DataGrid,它们的行非常快地更新了。每行都有一个右键单击事件,如果单击该事件,则应将所选行添加到另一个dataGrid。 问题是当用户选择一行以添加到另一个列表时 由于更新了所选行,他无法添加,因此用户应一次又一次选择该行。 我的代码是这样的
<DataGrid SelectionMode="Single" CanUserAddRows="False"CanUserDeleteRows="False" >
<DataGrid.Columns>
<DataGridTextColumn Header="Data1" Binding="{Binding Path=Data1}"></DataGridTextColumn>
<DataGridTextColumn Header="Data2" Binding="{Binding Path=Data2}"></DataGridTextColumn>
<DataGridTextColumn Header="Data3" Binding="{Binding Path=Data3}"></DataGridTextColumn>
<DataGridTextColumn Header="Data4" Binding="{Binding Path=Data4}"></DataGridTextColumn>
<DataGridTextColumn Header="Data5" Binding="{Binding Path=Data5}"></DataGridTextColumn>
<DataGridTextColumn Header="Data6" Binding="{Binding Path=Data6}"></DataGridTextColumn>
</DataGrid.Columns>
<DataGrid.ContextMenu>
<ContextMenu HorizontalContentAlignment="Right" FlowDirection="RightToLeft">
<MenuItem Name="addToBlackListMnuBtn" Header="Add to Black List" Click="addToBlackListMnuBtn_Click" FontWeight="Black"/>
<MenuItem Name="addtoReportedListMnuBtn" Header="Add to Reported List" Click="addtoReportedListMnuBtn_Click" FontWeight="Black"/>
</ContextMenu>
</DataGrid.ContextMenu>
</DataGrid>
当我想从contexMenu中单击“ addtoReportedListMnuBtn”时,我应该尝试几次以完成其事件。通常在下面的代码中显示messageBox
private void addtoReportedListMnuBtn_Click(object sender, RoutedEventArgs e)//add to reported list
{
ObjClass en = (ObjClass)ActiveSignalDataGrid.SelectedItem;
if(en!=null)
{
ReportSignalsListQ.Data = en; // add to queue for adding
}else
{
MessageBox.Show("Please select again");
}
}
答案 0 :(得分:0)
我想说,DataGrid
在您的情况下对ContextMenu
是错误的地方。将您的ContextMenu
放入窗口的资源中,并用于DataGridCell
。
<Window.Resources>
<ContextMenu x:Key="contMen" HorizontalContentAlignment="Right" FlowDirection="RightToLeft">
<MenuItem Name="addToBlackListMnuBtn" Header="Add to Black List" Click="addToBlackListMnuBtn_Click" FontWeight="Black"/>
<MenuItem Name="addtoReportedListMnuBtn" Header="Add to Reported List" Click="addtoReportedListMnuBtn_Click" FontWeight="Black"/>
</ContextMenu>
</Window.Resources>
<DataGrid.Resources>
<Style TargetType="DataGridCell">
<Setter Property="ContextMenu" Value="{StaticResource contMen}"/>
</Style>
</DataGrid.Resources>
private void addtoReportedListMnuBtn_Click(object sender, RoutedEventArgs e)//add to reported list
{
var en = (((sender as MenuItem).Parent as ContextMenu).PlacementTarget as DataGridCell).DataContext as ObjClass;
if (en != null)
{
ReportSignalsListQ.Data = en; // add to queue for adding
}
else
{
MessageBox.Show("Please select again");
}
}
答案 1 :(得分:0)
当您的ItemSource
更新时,您的SelectedItem
的{{1}}被清除。因此,您可以将DataGrid
事件添加到SelectionChanged
中,然后需要将DataGrid
分配给后面代码中的局部变量,然后将局部变量添加到第二个{{1 }}。