我有两个简单的Model类和一个ViewModel ...
public class GridItem
{
public string Name { get; set; }
public int CompanyID { get; set; }
}
public class CompanyItem
{
public int ID { get; set; }
public string Name { get; set; }
}
public class ViewModel
{
public ViewModel()
{
GridItems = new ObservableCollection<GridItem>() {
new GridItem() { Name = "Jim", CompanyID = 1 } };
CompanyItems = new ObservableCollection<CompanyItem>() {
new CompanyItem() { ID = 1, Name = "Company 1" },
new CompanyItem() { ID = 2, Name = "Company 2" } };
}
public ObservableCollection<GridItem> GridItems { get; set; }
public ObservableCollection<CompanyItem> CompanyItems { get; set; }
}
...和一个简单的窗口:
<Window x:Class="DataGridComboBoxColumnApp.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Grid>
<DataGrid AutoGenerateColumns="False" ItemsSource="{Binding GridItems}" >
<DataGrid.Columns>
<DataGridTextColumn Binding="{Binding Name}" />
<DataGridComboBoxColumn ItemsSource="{Binding CompanyItems}"
DisplayMemberPath="Name"
SelectedValuePath="ID"
SelectedValueBinding="{Binding CompanyID}" />
</DataGrid.Columns>
</DataGrid>
</Grid>
</Window>
DataContext
在App.xaml.cs中,ViewModel设置为MainWindow :
public partial class App : Application
{
protected override void OnStartup(StartupEventArgs e)
{
base.OnStartup(e);
MainWindow window = new MainWindow();
ViewModel viewModel = new ViewModel();
window.DataContext = viewModel;
window.Show();
}
}
如您所见,我将ItemsSource
DataGrid的设置GridItems
为ViewModel的集合。此部分有效,显示名称为“ Jim”的单个网格线。
我还想ItemsSource
将ComboBox的每一行都设置CompanyItems
为ViewModel的集合。这部分不起作用:ComboBox保持为空,并且在Debugger Output窗口中,我看到一条错误消息:
System.Windows.Data错误:2:找不到目标元素的管理FrameworkElement或FrameworkContentElement。BindingExpression:Path = CompanyItems; DataItem = null; 目标元素是“ DataGridComboBoxColumn”(HashCode = 28633162);目标属性为“ ItemsSource”(类型为“ IEnumerable”)
我相信WPF期望CompanyItems
不是这种属性,GridItem
这就是绑定失败的原因。
我已经尝试过使用RelativeSource
和,AncestorType
例如:
<DataGridComboBoxColumn ItemsSource="{Binding CompanyItems,
RelativeSource={RelativeSource Mode=FindAncestor,
AncestorType={x:Type Window}}}"
DisplayMemberPath="Name"
SelectedValuePath="ID"
SelectedValueBinding="{Binding CompanyID}" />
但这给了我调试器输出中的另一个错误:
System.Windows.Data错误:4:找不到参考'RelativeSource FindAncestor,AncestorType ='System.Windows.Window',AncestorLevel ='1''的绑定源。BindingExpression:Path = CompanyItems; DataItem = null; 目标元素是'DataGridComboBoxColumn'(HashCode = 1150788); 目标属性为“ ItemsSource”(类型为“ IEnumerable”)
问题:如何将DataGridComboBoxColumn的ItemsSource绑定到ViewModel的CompanyItems集合?有可能吗?
预先感谢您的帮助!