如何在C#中从DataGrid获取selectedRow数据

时间:2017-06-19 09:24:39

标签: c# wpf dictionary datagrid

我将字典绑定到我的DataGrid。现在我想从DataGrid中获取所选行。这是我到现在为止所做的。

Dictionary<int, string> dicKeyValue = new Dictionary<int, string>();

public MainWindow()
    {
        InitializeComponent();

        dataGrid.DataContext = dicKeyValue;

        dicKeyValue.Add(1, "INDIA");
        dicKeyValue.Add(2, "CHINA");
        dicKeyValue.Add(3, "AMERICA");
        dicKeyValue.Add(4, "RUSSIA");

    }

private void dataGrid_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        var sample = (sender as DataGrid).SelectedItem as ******
       // Here in the above line what should I write to get the values of selected row.

        if (sample != null)
        {

        }


    }

调试时我在立即窗口中尝试了这个......

((sender as DataGrid).SelectedItem)
{[8, SCAN]}
Key: 8
Value: "SCAN"
key: 8
value: "SCAN"

现在你们可以帮助我如何访问这个......

我的问题可能与this 类似,但在我的问题中,我想知道我可以将SelectedItem转换为正确的类型。

2 个答案:

答案 0 :(得分:2)

Dictionary<TKey, TValue>会继承ICollection<KeyValuePair<TKey, TValue>>,因此您的项目类型应为KeyValuePair<int, string>。出于投射目的,您可以使用Nullable<T>

var item = dataGrid.SelectedItem as KeyValuePair<int, string>?;
if (item.HasValue) // use item.Value

但是,使用dataGrid.SelectedValuePath = "Key"然后引用dataGrid.SelectedValue代替SelectedItem可能是值得的。

答案 1 :(得分:2)

这应该有效:

private void dataGrid_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    DataGrid dataGrid = sender as DataGrid;
    if (dataGrid.SelectedItem != null)
    {
        var sample = (KeyValuePair<int, string>)dataGrid.SelectedItem;
        int key = sample.Key;
        string value = sample.Value;
    }
}