带有组合框的MVVM数据绑定Datagrid/其他itemsource [英] MVVM Databinding Datagrid with Combobox / different itemsource
本文介绍了带有组合框的MVVM数据绑定Datagrid/其他itemsource的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个供用户输入的数据网格,每个单元格都是一个用于选择数据的组合框.所选值应绑定到数据网格的itemsource,以将数据稍后保存到我的数据库中.组合框值应来自其他项目来源.
I have a datagrid for user input and each cell is a combobox for data selection. The selected value shall be binded to the itemsource of the datagrid to save the data later into my database. The combobox values shall come from a different itemsource.
UI:
<DataGrid ItemsSource="{Binding Users}">
<DataGrid.Columns>
<DataGridTemplateColumn Header="Firstname">
<DataGridTemplateColumn.CellTemplate>
<HierarchicalDataTemplate>
<ComboBox ItemsSource="{Binding Firstnames}" DisplayMemberPath="Name"/>
</HierarchicalDataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
</DataGrid.Columns>
</DataGrid>
<ComboBox ItemsSource="{Binding Firstnames}" DisplayMemberPath="Name">
</ComboBox>
</StackPanel>
模型和ViewModel:
Model and ViewModel:
// Models
public class User
{
public string Firstname { get; set; }
public string Lastname {get; set; }
}
public class Firstname
{
public string Name { get; set; }
}
public class Lastname
{
public string Name { get; set; }
}
//ViewModel
public class GenerateViewModel : NotifyUIBase
{
#region properties
public ObservableCollection<User> Users { get; set; }
public ObservableCollection<Firstname> Firstnames { get; set; }
public ObservableCollection<Lastname> Lastnames { get; set; }
#endregion
#region Constructor
public GenerateViewModel()
{
Firstnames = new ObservableCollection<Firstname>()
{
new Firstname() {Name="Firstname1"},
new Firstname() {Name= "Firstname2"}
};
Lastnames = new ObservableCollection<Lastname>()
{
new Lastname() {Name="Lastname1"},
new Lastname() {Name= "Lastname2"}
};
Users = new ObservableCollection<User> {new User()};
}
#endregion
#region Methods
#endregion
}
datagrid内部的组合框保持为空,但是我与datagrid外部的其他组合框的绑定效果很好.
The combobox inside of the datagrid keeps empty, but my binding with a additional combobox outside of the datagrid works well.
推荐答案
无法识别DataContext,您必须从主窗口获取它:
DataContext is not recognized, you have to get it from the main Window:
<HierarchicalDataTemplate>
<ComboBox ItemsSource="{Binding RelativeSource={RelativeSource FindAncestor,
AncestorType={x:Type Window}},
Path=DataContext.Firstnames}"
DisplayMemberPath="Name"/>
</HierarchicalDataTemplate>
这篇关于带有组合框的MVVM数据绑定Datagrid/其他itemsource的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文