【发布时间】:2021-10-18 10:36:39
【问题描述】:
我正在WPF (MVVM) 中构建一个应用程序。
用户将在ComboBox 中进行选择,并且该选择应该过滤DataGridComboBoxColumn (DGCBC) 中的DataGrid 中可用的结果。
但我不知道如何将ComboBox SelectedItem 绑定到 DGCBC。我确实设法让ComboBox 过滤了第二个ComboBox 的结果,但该逻辑似乎无法很好地转移到 DGCBC。
我尝试过的:
我的ComboBox:
<ComboBox
DisplayMemberPath="PropertyName1"
ItemsSource="{Binding Collection1}"
Loaded="{s:Action NameOfMethodToPopulateComboBox}"
SelectedItem="{Binding PropertyHolder, UpdateSourceTrigger=PropertyChanged}"/>
PropertyHolder 在ComboBox 中选择项目时运行,如果它不为空,则运行添加到绑定到 DGCBC 的ObservableCollection 的方法。它看起来像这样:
private ClassName _currentSelectedItem;
public ClassName CurrentSelectedItem {
get { return this,._selectedItem; }
set { SetAndNotify(ref this._selectedItem, value);
if (value != null) {
FillDataGridComboBoxColumn();
}
}
}
方法,FillDataGridComboBoxColumn() 看起来像这样(缩写):
DataSet ds = new();
// Code to run stored procedure
// CurrentSelectedItem is given as parameter value
DataTable dt = new();
dt = ds.Tables[0];
MyObservableCollection.Clear();
for (int i = 0; i < dt.Rows.Count; i++) {
DataRow dr = dt.NewRow();
dr = dt.Rows[i];
HolderClass holderClass = new(); // this is the class that is bound to the observablecollection
holderClass.PropertyName = dr["PropertyName2"].ToString();
MyObservableCollection.Add(holderClass);
这是 DataGrid 和 DataGridComboBoxColumn 的 XAML:
<DataGrid
AutoGenerateColumns="False"
ItemsSource="{Binding MyObservableCollection}">
<DataGridComboBoxColumn
SelectedValueBinding="{Binding PropertyName2, UpdateSourceTrigger=PropertyChanged}"
SelectedValuePath="PropertyName2"
DisplayMemberPath="PropertyName2"
ItemsSource="{Binding MyObservableCollection}">
/>
</DataGrid>
当我调试时,DataGridComboBoxColumn 能够获得正确的行数 - 但它们只是空占位符;空白。如果我在代码中设置断点,我会看到集合确实加载了正确的值,但它们只是没有显示。
我猜我对 DGCBC 的绑定做错了。
谢谢。
【问题讨论】:
-
您没有绑定
DataGridComboBoxColumn.ItemSource。而且我真的不明白 DataGrid 和 DGCBC 列应该显示什么?也许您应该显示更多代码,例如过滤哪些集合以及用户如何选择组合框中的项目? -
PropertyHolder是如何实现的,您如何实际填充DataGrid中的ComboBox?你的例子没有说明。 -
@mm8,感谢您的评论。你是对的 - 我已经更新了我的问题。
-
TextColumn 显示数据源中一行的单个属性。 ComboBox 具有 mpre 项(使用 ItemsSource 指定),其中一项 SelectedItem 与数据网格中数据行的属性相匹配。我仍然不了解您的目标,但是如果 DataGridComboBoxColumn 中没有 ItemSource,您将没有任何项目可供选择。
-
不,没有好转。正如我所说,如果您不将某些具有名为“Property2”的属性的对象集合绑定到 DataGridComboBoxColumn 的 ItemSource,则不会显示任何内容。另外,看看 Visual Studio 中的输出窗口,我相信你会在那里发现绑定错误。
标签: c# wpf mvvm combobox datagrid