c# - WPF 将 DataGridComboBoxColumn 绑定到 ComboBox 的 SelectedItem
问题描述
我正在WPF
(MVVM)中构建一个应用程序。用户要在 a 中进行选择ComboBox
,并且该选择应该过滤 a 中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
,如果它不为空,则运行添加到ObservableCollection
绑定到 DGCBC 的方法。它看起来像这样:
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
XAML DataGridComboBoxColumn
:
<DataGrid
AutoGenerateColumns="False"
ItemsSource="{Binding MyObservableCollection}">
<DataGridComboBoxColumn
SelectedValueBinding="{Binding PropertyName2, UpdateSourceTrigger=PropertyChanged}"
SelectedValuePath="PropertyName2"
DisplayMemberPath="PropertyName2"
ItemsSource="{Binding MyObservableCollection}">
/>
</DataGrid>
当我调试时,DataGridComboBoxColumn
能够获得正确的行数 - 但它们只是空占位符;空白。如果我在代码中设置断点,我会看到集合确实加载了正确的值,但它们只是没有显示。
我猜我对 DGCBC 的绑定做错了。
谢谢你。
解决方案
DataGridComboBoxColumn
ItemSource
必须设置Static Resource
为:
<Window.Resources>
<CollectionViewSource x:Key="MyObservableCollection" Source="{Binding MyObservableCollection}"/>
</Window.Resources>
然后,在 XAML 中DataGridComboBoxColumn
:
<DataGridComboBoxColumn
ItemsSource="{Binding Source={StaticResource MyObservableCollection}}"
DisplayMemberPath="Property2">
</DataGridComboBoxColumn>
推荐阅读
- javascript - 使用外部范围与内部范围的函数之间的区别?
- java - OpenCV 结构光 getProjPixel() 示例
- python - 数据框中的对象值的 KeyError
- linux - Dockerfile 中的 setfacl 没有效果
- android - 如何保存 EditText 组件中的数据,以便在重新打开应用程序时显示?
- sql - Oracle 屏蔽字符串中一组字符的多个实例 - 字符串中“要屏蔽的短语”的多种变体
- c++ - 如何在 gradle 本机项目中包含二进制库?
- javascript - Salesforce:在 Lightning 组件中动态获取记录 ID
- amazon-web-services - AWS Parameter store 是针对每个键还是整个服务的吞吐量限制?
- java - 如何使用opencsv将csv解析为按列分组的hashmap