【发布时间】:2016-10-08 12:01:29
【问题描述】:
我有一个绑定到 ObservableCollection (StoredSequences<Sequence>) 的 DataGrid:
<DataGrid ItemsSource="{Binding StoredSequences}">
<DataGrid.Columns>
<DataGridTextColumn Binding="{Binding ID}" >
<DataGridTextColumn.ElementStyle>
<Style>
<Setter Property="TextBlock.TextWrapping" Value="Wrap" />
<Setter Property="TextBlock.TextAlignment" Value="Center"/>
</Style>
</DataGridTextColumn.ElementStyle>
</DataGridTextColumn>
<DataGridTextColumn Binding="{Binding NameEnglish}" >
<DataGridTextColumn.ElementStyle>
<Style>
<Setter Property="TextBlock.TextWrapping" Value="Wrap" />
</Style>
</DataGridTextColumn.ElementStyle>
</DataGridTextColumn>
</DataGrid.Columns>
</DataGrid>
序列模型:
public class Sequence : INotifyPropertyChanged
{
public Sequence() { }
private int _id;
public int ID
{
get
{
return _id;
}
set
{
_id = value;
OnPropertyChanged("ID");
}
}
private string _nameEnglish;
public string NameEnglish
{
get
{
return _nameEnglish;
}
set
{
_nameEnglish = value;
OnPropertyChanged("NameEnglish");
}
}
private int _value;
public int Value
{
get
{
return _value;
}
set
{
_value= value;
OnPropertyChanged("Value");
}
}
private string _category;
public string Category
{
get
{
return _category;
}
set
{
_category = value;
OnPropertyChanged("Category");
}
}
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged(string propertyName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
我想在网格的最后两列中添加两个 ComboBox,并将 ItemsSource 绑定到其他 ObservableCollections(在 ViewModel 中生成Values<int> 和 Categories<string>)。我可以添加文本框,因为Sequence 包含Value 和Category,但我希望用户能够选择这些项目。我试过这个:
<DataGridTemplateColumn>
<DataGridTemplateColumn.CellEditingTemplate>
<DataTemplate>
<ComboBox x:Name="ComboBox1" ItemsSource="{Binding Values}" />
</DataTemplate>
</DataGridTemplateColumn.CellEditingTemplate>
</DataGridTemplateColumn>
<DataGridTemplateColumn>
<DataGridTemplateColumn.CellEditingTemplate>
<DataTemplate>
<ComboBox x:Name="ComboBox2" ItemsSource="{Binding Categories}"/>
</DataTemplate>
</DataGridTemplateColumn.CellEditingTemplate>
</DataGridTemplateColumn>
问题是组合框是空的。这是收到的错误之一:
System.Windows.Data Error: 40 : BindingExpression path error: 'Values' property not found on 'object' ''Sequence' (HashCode=31195541)'. BindingExpression:Path=Values; DataItem='Sequence' (HashCode=31195541); target element is 'ComboBox' (Name=ComboBox1'); target property is 'ItemsSource' (type 'IEnumerable')
将 DataGrid 绑定到更多集合的正确方法是什么?或者我怎样才能在 CellEdit 和 TextBox 上显示 ComboBoxes?
【问题讨论】:
-
StoredSequencesObservableCollection存储StoredSequences-es 或Sequence?我不完全明白。顺便说一句,我会像StoredSequences那样做ObservableCollection的视图模型 -
@ntohl 它存储序列。
-
你能粘贴序列类吗?我对 Values 和 Categories 属性感兴趣
标签: c# wpf xaml datagrid observablecollection