我有一个用于用户输入的数据网格,每个单元格都是用于数据选择的组合框。所选值应绑定到datagrid的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:
// 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
}
数据网格内部的组合框保持为空,但我与数据网格外部的其他组合框的绑定效果很好。
答案 0 :(得分:1)
无法识别DataContext,您必须从主窗口获取它:
<HierarchicalDataTemplate>
<ComboBox ItemsSource="{Binding RelativeSource={RelativeSource FindAncestor,
AncestorType={x:Type Window}},
Path=DataContext.Firstnames}"
DisplayMemberPath="Name"/>
</HierarchicalDataTemplate>