WPF Datagrid Get Selected Cell Value

前端 未结 12 2057
遇见更好的自我
遇见更好的自我 2020-11-30 08:47

I want to get value for selected cell in datagrid , please anyone tell how to do this. i used SelectedCell changed event , how can i do that?

dataGrid1.Curre         


        
12条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-11-30 09:45

    If SelectionUnit="Cell" try this:

        string cellValue = GetSelectedCellValue();
    

    Where:

        public string GetSelectedCellValue()
        {
            DataGridCellInfo cellInfo = MyDataGrid.SelectedCells[0];
            if (cellInfo == null) return null;
    
            DataGridBoundColumn column = cellInfo.Column as DataGridBoundColumn;
            if (column == null) return null;
    
            FrameworkElement element = new FrameworkElement() { DataContext = cellInfo.Item };
            BindingOperations.SetBinding(element, TagProperty, column.Binding);
    
            return element.Tag.ToString();
        }
    

    Seems like it shouldn't be that complicated, I know...

    Edit: This doesn't seem to work on DataGridTemplateColumn type columns. You could also try this if your rows are made up of a custom class and you've assigned a sort member path:

        public string GetSelectedCellValue()
        {
            DataGridCellInfo cells = MyDataGrid.SelectedCells[0];
    
            YourRowClass item = cells.Item as YourRowClass;
            string columnName = cells.Column.SortMemberPath;
    
            if (item == null || columnName == null) return null;
    
            object result = item.GetType().GetProperty(columnName).GetValue(item, null);
    
            if (result == null) return null;
    
            return result.ToString();
        }
    

提交回复
热议问题