问题描述
这让我疯狂了我有一个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绑定到Goal类型的对象集合。每个目标都有一个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和LifeArea: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();
当我有机会将其转换为StaticResource。
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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!