我正在尝试将T的ObservableCollection绑定到DataGrid的DataGridComboBoxColumn。
DataGrid定义为:
<DataGrid AutoGenerateColumns="False" ItemsSource="{Binding Model, IsAsync=True}">
<DataGrid.Columns>
<DataGridTextColumn Header="Column Entry" IsReadOnly="True" Binding="{Binding ColumnName}"/>
<DataGridComboBoxColumn Header="Road Type" ItemsSource="{Binding RoadTypes}"/>
</DataGrid.Columns>
</DataGrid>这是ViewModel和模型
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
var viewModel = new ViewModel();
DataContext = viewModel;
}
}
public class ViewModel : ViewModelBase
{
private ObservableCollection<Model> _model;
public ViewModel()
{
var list = new List<Model>();
var roadTypes = new ObservableCollection<RoadType>
{
new RoadType
{
Code = 1,
Id = 1,
Name = "Name1"
},
new RoadType
{
Code = 1,
Id = 1,
Name = "Name1"
}
};
Model = new ObservableCollection<Model>
{
new Model
{
ColumnName = "Col1",
RoadTypes = roadTypes
},
new Model
{
ColumnName = "Col1",
RoadTypes = roadTypes
}
};
}
public ObservableCollection<Model> Model
{
get { return _model; }
set
{
_model = value;
RaisePropertyChanged(() => Model);
}
}
}
public class RoadType
{
public int Id { get; set; }
public int Code { get; set; }
public string Name { get; set; }
}
public class Model : ObservableObject
{
private ObservableCollection<RoadType> _roadTypes;
public string ColumnName { get; set; }
public ObservableCollection<RoadType> RoadTypes
{
get { return _roadTypes; }
set
{
_roadTypes = value;
RaisePropertyChanged(() => RoadTypes);
}
}
}DataGrid也显示文本列,但它不显示ComboBox值。
怎么了?
发布于 2013-04-30 23:09:23
因为RoadTypes不是一个简单的字符串列表,所以您需要告诉您的组合框它需要在ComboBox中显示什么属性。尝试添加
DisplayMemberPath="Name" 添加到您的combobox声明
--
更新:
好的,这是WPF数据网格的一个已知的“特性”。问题是DataGridComboBox没有DataGrid的DataContext。我修改了ComboBox的绑定,使其如下所示:
<DataGridComboBoxColumn DisplayMemberPath="Name">
<DataGridComboBoxColumn.ElementStyle>
<Style>
<Setter Property="ComboBox.ItemsSource" Value="{Binding Path=RoadTypes}" />
</Style>
</DataGridComboBoxColumn.ElementStyle>
<DataGridComboBoxColumn.EditingElementStyle>
<Style>
<Setter Property="ComboBox.ItemsSource" Value="{Binding Path=RoadTypes}" />
</Style>
</DataGridComboBoxColumn.EditingElementStyle>
</DataGridComboBoxColumn>我修改了下载链接中提供的代码,当我打开combobox下拉菜单时,combobox项就会显示出来。
请查看其中一些链接以获得进一步的澄清:
http://social.msdn.microsoft.com/Forums/en-US/wpf/thread/b4b13a72-47f9-452f-85c6-6c4b5b606df5/
How to bind collection to WPF:DataGridComboBoxColumn
Excedrin headache #3.5.40128.1: Using combo boxes with the WPF DataGrid
导致我查看所有这些站点的原因是查看输出窗口,并注意到错误消息System.Windows.Data Error: 2: Cannot find FrameworkElement or FrameworkContentElement for target element。消息
https://stackoverflow.com/questions/16303114
复制相似问题