Wpf中的DataGrid选定项 [英] DataGrid Selected Item in Wpf

查看:81
本文介绍了Wpf中的DataGrid选定项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Hi


当我第一次在DataGrid中选择一行时,SelectedItem获取值。再次,如果我在dataGrid中选择相同的行,则selectedItem变为null。请给出一些想法...



< DataGrid Name =   dgDbConnection ItemsSource =   {Binding ObjDBConnectionObsvList} SelectedItem =   {Binding ObjDBConnectionSelectedDatam,Mode = TwoWay} / 

>

解决方案





这是 DataGrid ,您可以在 DataGrid 中选择和取消选择一行。



要防止这种情况,请收听 DataGrid.SelectionChanged 事件。



在事件处理程序中,您可以输入例如:



  private   void  SelectionChanged( object  sender,SelectionChangedEventArgs e) 
{
DataGrid g = sender as DataGrid;

// 检查是否没有添加行(到选定的行)
// 但是从网格的选定行中删除了至少1行
if (g!= null && e.AddedItems.Count == 0 && e.RemovedItems.Count > 0
{
// 这将选择e.RemovedItems集合中的第一行
g.SelectedItem = e.RemovedItems [ 0 ];
}
}





这可以防止取消选择行。



希望这会有所帮助。



问候,



托马斯。


Hi
When I Select a row in DataGrid for first time SelectedItem gets the value. Again if i select the same row in dataGrid then the selectedItem became null. Please give some idea...

<DataGrid Name="dgDbConnection"ItemsSource="{Binding ObjDBConnectionObsvList}" SelectedItem="{Binding ObjDBConnectionSelectedDatam,Mode=TwoWay}"/

>

解决方案

Hi,

this is the default behavior of the DataGrid, you can select and unselect a row in a DataGrid.

To prevent this, listen to the DataGrid.SelectionChanged event.

In the event handler you could type e.g.:

private void SelectionChanged(object sender, SelectionChangedEventArgs e)
{
   DataGrid g = sender as DataGrid;

   // checks if no rows where added (to the selected rows)
   // but at least 1 row removed from the selected rows of the grid
   if (g != null && e.AddedItems.Count == 0 && e.RemovedItems.Count > 0)
   {
      // this selects the first row in the e.RemovedItems collection
      g.SelectedItem = e.RemovedItems[0];
   }
}



This should prevent the deselection of the row.

Hope this helps.

Regards,

Thomas.


这篇关于Wpf中的DataGrid选定项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆