获取DataGrid Selected Row值绑定到WPF中的列表

时间:2016-05-22 03:12:00

标签: c# wpf datagrid

我有一个DataGrid,我通过列表绑定如下

<DataGrid Name="GridCoutry" AutoGenerateColumns="False" CanUserAddRows="False" CanUserDeleteRows="False" CanUserReorderColumns="False">
    <DataGrid.Columns>
        <DataGridTextColumn Header="ID" Binding="{Binding Id}" Width="*"/>
        <DataGridTextColumn Header="Country Name" Binding="{Binding CountryName}" Width="*"/>
        <DataGridTextColumn Header="Country Code" Binding="{Binding CountryCode}" Width="*"/>
        <DataGridTemplateColumn Header="Actions" Width="*">
            <DataGridTemplateColumn.CellTemplate>
                <DataTemplate>
                    <StackPanel Orientation="Horizontal">
                        <Button Content="Delete" Name="BtnDelete" Click="BtnDelete_Click" MinWidth="100" Margin="0,0,10,0"/>
                        <Button Content="Edit" x:Name="BtnEdit" Click="BtnEdit_Click" MinWidth="100" Margin="0,0,10,0"/>
                    </StackPanel>
                </DataTemplate>
            </DataGridTemplateColumn.CellTemplate>
        </DataGridTemplateColumn>
    </DataGrid.Columns>
</DataGrid>

我将DataGrid绑定如下

public static List<Country> GetCountryList()
{
    List<Country> CountryData = new List<Country>();
    using (var sr = new StreamReader(@"CountryCodes"))
    {
        string line;
        int i = 0;
        while ((line = sr.ReadLine()) != null)
        {
            i++;
            Country C_Data = new Country();
            int index = line.LastIndexOf(" ");
            C_Data.Id = i;
            C_Data.CountryName = line.Substring(0, index);
            C_Data.CountryCode = line.Substring(index + 1);
            CountryData.Add(C_Data);
        }
    }
    return CountryData;
}

并在窗口加载

GridCoutry.ItemsSource = GetCountryList();

enter image description here

我编写了以下代码来获取所选编辑按钮的CountryName

private void BtnEdit_Click(object sender, RoutedEventArgs e)
{
    var drv = GridCoutry.SelectedItem as DataRowView;
    if (drv == null) return;
    var CountryName = drv[1].ToString();
}

我的drv返回null但是当我看到GridCoutry.SelectedItem时,我得到了我想要的选定值。

不知道我哪里出错了?

1 个答案:

答案 0 :(得分:1)

您应该将所选项目转换为正确的类型。

Country selectedCountry = (Country)GridCoutry.SelectedItem;

另一个将SelectedItem绑定到您的类/ viewmodel

的选项
<Grid DataContext="<ViewModel Name>">
    <DataGrid ItemsSource="{Binding Path=Country}"
              SelectedItem="{Binding Path=SelectedCountry, Mode=TwoWay}"/>
</Grid>