【问题标题】:How to delete a row from DataGrid control in WPF?如何从 WPF 中的 DataGrid 控件中删除一行?
【发布时间】:2016-07-03 16:25:22
【问题描述】:

我知道我应该使用 PreviewKeyDown 事件来删除 DataGrid 中的一行,所以我在 UI 中有这段代码:

<DataGrid Name="dgPlaces"
            AutoGenerateColumns="True"
            ItemsSource="{Binding Places}"
            PreviewKeyDown="dgPlaces_PreviewKeyDown"
    />

然后我在代码隐藏中有这段代码:

private void dgPlaces_PreviewKeyDown(object sender, KeyEventArgs e)
{
    if (e.Key == Key.Delete)
    {
        if (dgPlaces.SelectedItems.Count > 0)
        {
            foreach (var row in dgPlaces.SelectedItems)
            {
                //here should be delete logic for each row
            }
        }
    }
}

我在 ViewModel 中有这段代码:

public class ViewModel //: INotifyPropertyChanged
{
    public ViewModel()
    {

    }

    private ObservableCollection<Place> places = new ObservableCollection<Place>()
    {
        new Place { Id = 1, City = "New York", Country = "US" },
        new Place { Id = 2, City = "Chicago", Country = "US" },
        new Place { Id = 3, City = "Miami", Country = "US" }
    };

    public ObservableCollection<Place> Places
    {
        get
        {
            return places;
        }
        set
        {
            places = value;
            RaisePropertyChanged("Places");
        }
    }
}

在 Model 类中,我有 Id、City 和 Country 属性:

public class Place
{
    public int Id { get; set; }
    public string City { get; set; }
    public string Country { get; set; }
}

我的问题与代码隐藏文件中的循环有关:如何从那里的行中提取 Id,以便应用程序知道应该删除哪一行?

foreach (var row in dgPlaces.SelectedItems)
{
    //here should be delete logic for each row
}

为什么我不能把 .在行之后而不是从 IntelliSense 获取 Id?没看懂。

【问题讨论】:

    标签: c# wpf xaml mvvm datagrid


    【解决方案1】:

    DataGrid.SelectedItems 属性是非泛型的,它只是 IListrow 具有 object 类型,除非像这样指定确切的类型:

    foreach (Place row in dgPlaces.SelectedItems)
    {
    
    }
    

    【讨论】:

      猜你喜欢
      • 2014-08-22
      • 1970-01-01
      • 2014-12-17
      • 2016-02-17
      • 2019-02-01
      • 1970-01-01
      • 2012-02-11
      • 2023-03-24
      • 1970-01-01
      相关资源
      最近更新 更多