如何使用 MVVM 将数据绑定到 DataGrid 中的 DataGridComboBoxColumn [英] How to Bind data to DataGridComboBoxColumn in DataGrid using MVVM
问题描述
这让我发疯.我有一个 DataGrid,它有一个 DataGridComboBoxColumn,我希望用户能够使用它进行选择.这是我的网格的基本轮廓.
This is driving me crazy. I have a DataGrid which has a DataGridComboBoxColumn which I want the user to be able to use to select from. This is the basic outline of my grid.
<DataGrid ItemsSource="{Binding GoalList}" DockPanel.Dock="Bottom" AutoGenerateColumns="False">
<DataGrid.Columns>
<DataGridComboBoxColumn ItemsSource="{Binding LifeAreaList}" Header="Life Area"/>
<DataGrid.Columns>
</DataGrid>
DataGrid 绑定到目标类型的对象集合.每个目标都有一个 LifeArea 类型的属性.每个 LifeArea 都有 LifeAreaId 和 Name 属性.
The DataGrid is bound to a collection of objects of type Goal. Each Goal has a property of type LifeArea. Each LifeArea has the properties LifeAreaId and Name.
数据上下文包含一个可观察的目标集合:GoalList 和一个生活领域列表:LifeAreaList.我希望用户能够为一个目标选择不同的生活领域.另外生活区的名称需要是显示值.
The data context contains an observable collection of Goals: GoalList and a list of Life Areas: LifeAreaList. I want the user to be able to select a different life area for a goal. Also the name of the life area needs to be the displayed value.
编辑
解决方案是必须将 DataGridComboBoxColumn 的 ItemsSource 设置为静态资源.另一种选择是通过代码设置ItemsSource.
The solution is that the ItemsSource for the DataGridComboBoxColumn has to be set as a static resource. Another option is to set the ItemsSource through code.
最后我有:
<DataGridComboBoxColumn x:Name="_lifeAreaComboBoxColumn" SelectedItemBinding="{Binding LifeArea}" DisplayMemberPath="Name" Header="Life Area">
在后面的代码中我设置了ItemsSource:
In the code behind I set the ItemsSource:
_lifeAreaComboBoxColumn.ItemsSource = LifeAreaDAL.GetLifeAreas();
有机会我会将其转换为静态资源.
When I get a chance I'll convert this to a StaticResource.
推荐答案
你需要做这样的事情(不要拍使者):
You need to do something like this (don't shoot the messenger):
<DataGridComboBoxColumn Header="Life Area" SelectedItemBinding="{Binding SelectedLifeArea}">
<DataGridComboBoxColumn.ElementStyle>
<Style TargetType="ComboBox">
<Setter Property="ItemsSource" Value="{Binding LifeAreaList}"/>
<Setter Property="IsReadOnly" Value="True"/>
</Style>
</DataGridComboBoxColumn.ElementStyle>
<DataGridComboBoxColumn.EditingElementStyle>
<Style TargetType="ComboBox">
<Setter Property="ItemsSource" Value="{Binding LifeAreaList}"/>
</Style>
</DataGridComboBoxColumn.EditingElementStyle>
</DataGridComboBoxColumn>
这篇关于如何使用 MVVM 将数据绑定到 DataGrid 中的 DataGridComboBoxColumn的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!