设置DataGridComboBoxColumn所选项目
问题描述:
我想在DataGridComboBoxColumn
中将特定项目设置为selectedItem。然而,很多研究,我还没有找到正确的答案。设置DataGridComboBoxColumn所选项目
我的情景:
我有一个编程创建一个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"
...
}
我发现很多教程,用于设置正常组合框所选的项目,而不是DataGridComboBoxColumns。我已经试过currencies.SetCurrentValue()
,但我找不到合适的DependencyProperty
DataGridComboBoxColumn
。
有人可以帮我吗?
在此先感谢。
Boldi
答
像C#代码那样构建一个DataGrid很混乱。你应该看看使用数据绑定来代替。如果你想继续用C#构建它,那么你将不得不设置行的值。没有办法为列中的所有行设置默认值。假设我的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#世界很陌生。 – Boldi