用不同类型绑定ComboBox中的SelectedItem [英] Binding SelectedItem of ComboBox in DataGrid with different type
问题描述
我有一个DataGrid,其中包含ComboBox作为列。
I have a DataGrid which contains ComboBox as column.
让我们考虑将ItemsSource作为ObservableCollection并且ComboBox ItemsSource是List的DataGrid。
Let consider DataGrid having ItemsSource as ObservableCollection and ComboBox ItemsSource is List .
我要设置ComboBox SelectedItem属性基于DataGrid ItemsSource中的属性。
I want to set the ComboBox SelectedItem property based on property in DataGrid ItemsSource.
但是Product类的属性ProductTypeId的类型为int而不是ProductType。
However Product class has property ProductTypeId of type int and not ProductType.
所以我该如何设置ComboBox SelectedItem以便将 Product.ProductTypeId的值显示为选中状态。
而且我还想将SeletedItems与Mode = TwoWay绑定,以便每当ComboBox SelectedItem更改时,它将反映在DataGrid的ItemsSource中。
So how can I set ComboBox SelectedItem so that it display value of Product.ProductTypeId as selected. And also I want to bind SeletedItems with Mode = TwoWay so that whenever ComboBox SelectedItem changes it will be reflected in DataGrid's ItemsSource.
任何帮助将不胜感激。
谢谢。
推荐答案
DataGridComboBoxColumn
完全可以满足您的需求。要正确使用它,您需要了解以下属性:
The DataGridComboBoxColumn
does exactly what you're looking for. To use it correctly, you need to understand the following properties:
-
SelectedValueBinding
-这是对对象/视图模型上属性的绑定 -
SelectedValuePath
-这是<$内部项目的value属性c $ c> ComboBox 。当用户从ComboBox
中选择一个项目时,它将分配给您在SelectedValueBinding
中设置的属性。 -
DisplayMemberPath
-这是ComboBox
SelectedValueBinding
- this is the binding to the property on your object/viewmodelSelectedValuePath
- this is the value property on the items inside theComboBox
. This will be assigned to the property you set inSelectedValueBinding
when the user selects an item from theComboBox
.DisplayMemberPath
- this is the description property on the items inside theComboBox
设置 DataGridComboBoxColumn $ c $的
ItemsSource
c>有点不同;请注意下面的示例以了解其操作方法。
Setting the ItemsSource
of the DataGridComboBoxColumn
is a little different; note my example below to see how it is done.
这些与您相同(除了 SelectedValueBinding
)在标准的 ComboBox
中。
These are the same (except for SelectedValueBinding
) as you have on a standard ComboBox
.
以下是您的列的示例。
<DataGridComboBoxColumn Header="Product Type" DisplayMemberPath="ProductType" SelectedValuePath="ProductTypeId" SelectedValueBinding="{Binding ProductTypeId, UpdateSourceTrigger=PropertyChanged}">
<DataGridComboBoxColumn.ElementStyle>
<Style TargetType="{x:Type ComboBox}">
<Setter Property="ItemsSource" Value="{Binding AvailableProductTypes}"/>
<Setter Property="VerticalAlignment" Value="Center"/>
</Style>
</DataGridComboBoxColumn.ElementStyle>
<DataGridComboBoxColumn.EditingElementStyle>
<Style TargetType="{x:Type ComboBox}">
<Setter Property="ItemsSource" Value="{Binding AvailableProductTypes}"/>
<Setter Property="VerticalAlignment" Value="Center"/>
</Style>
</DataGridComboBoxColumn.EditingElementStyle>
</DataGridComboBoxColumn>
这篇关于用不同类型绑定ComboBox中的SelectedItem的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!