【问题标题】:Set DataGridComboBoxColumn selected item设置 DataGridComboBoxColumn 选中项
【发布时间】:2016-12-30 07:13:52
【问题描述】:

我正在尝试将特定项目设置为 DataGridComboBoxColumn 中的 selectedItem。然而,经过大量研究,我还没有找到适合我的正确答案。

我的场景:
我有一个以编程方式创建的DataGrid,它的ObservableCollection<>ItemsSource。作为最后一列,我想添加一个DataGridComboBoxColumn 给用户一个可供选择的选项。由于此类数据已经可以存储在数据库中,因此我需要从存储在数据库中的集合中“预设”值。

private void ManipulateColumns(DataGrid grid)
{
    ...
    DataGridComboBoxColumn currencies = new DataGridComboBoxColumn();
    //Here come the possible choices from the database
    ObservableCollection<string> allCurrencies = new ObservableCollection<string>(Data.AllCurrencys); 
    currencies.ItemsSource = allCurrencies;
    currencies.Header = "Currency";
    currencies.CanUserReorder = false;
    currencies.CanUserResize = false;
    currencies.CanUserSort = false;
    grid.Columns.Add(currencies);
    currencies.MinWidth = 100;
    //Set the selectedItem here for the column "Currency"
    ...
}

我找到了很多关于为普通 ComboBoxes 设置所选项目的教程,但不是为 DataGridComboBoxColumns 设置的。我已经用currencies.SetCurrentValue() 试过了,但是我从DataGridComboBoxColumn 找不到合适的DependencyProperty
有人可以帮帮我吗?

提前致谢。
博尔迪

【问题讨论】:

    标签: c# wpf datagrid observablecollection datagridcomboboxcolumn


    【解决方案1】:

    使用 C# 代码构建这样的 DataGrid 很麻烦。您应该真正看看使用数据绑定。如果您想继续在 C# 中构建它,那么您将不得不为每个 Row 设置值。没有办法为列中的所有行设置默认值。假设我的 DataGrid 绑定到 Book 类型的集合。我可以使用 DataGrid SelectedItem 属性来获取所选行的 Book 对象,然后设置它的货币属性。您将必须弄清楚需要为哪一行设置值,获取该行的对象,然后设置其货币属性。这不是一个完整的答案,但它会让你开始。本质上,您必须为 DataGrid 中的每个项目设置它,而不是列。

    public class  Book
    {
        public decimal price;
        public string title;
        public string author;
        public string currency;
    }
    
    private void ManipulateColumns(DataGrid grid)
    {
    
        DataGridComboBoxColumn currencies = new DataGridComboBoxColumn();
        //Here come the possible choices from the database
        System.Collections.ObjectModel.ObservableCollection<string> allCurrencies = new System.Collections.ObjectModel.ObservableCollection<string>();
        allCurrencies.Add("US");
        allCurrencies.Add("asdf");
        allCurrencies.Add("zzz");
        currencies.ItemsSource = allCurrencies;
        currencies.Header = "Currency";
        currencies.CanUserReorder = false;
        currencies.CanUserResize = false;
        currencies.CanUserSort = false;
        grid.Columns.Add(currencies);
        currencies.MinWidth = 100;
        //Set the selectedItem here for the column "Currency"
        //currencies.
    
        ((Book)grid.SelectedItem).currency = "US Dollar";
    }
    

    【讨论】:

    • 嗨布伦特,感谢您的回复。我的目标确实是从组合框中为每一行设置一个值。我不确定你所说的混乱是什么意思。我将尝试实现这一点,然后提供反馈。但这不是将数据绑定到DataGrid 的正常方式吗?我认为采用ObservableCollection 并将其设置为ItemsSource 是正确的方法。但我必须承认,我对 C# 世界还很陌生。
    猜你喜欢
    • 2020-05-05
    • 1970-01-01
    • 2015-08-06
    • 1970-01-01
    • 2023-03-14
    • 2023-03-21
    • 2021-05-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多