在WPF DataGrid中绑定ComboBoxColumn的ItemsSource
我有两个简单的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>
但是这给了我调试器输出中的另一个错误:
System.Windows.Data错误:4:无法找到绑定源,引用'RelativeSource FindAncestor,AncestorType ='System.Windows.Window',AncestorLevel ='1''。BindingExpression:路径= CompanyItems; 的DataItem = NULL; target元素是'DataGridComboBoxColumn'(HashCode = 1150788); target属性是'ItemsSource'(输入'IEnumerable')
问题:如何将DataGridComboBoxColumn的ItemsSource绑定到ViewModel的CompanyItems集合?有可能吗?
提前感谢您的帮助!
函数式编程
慕村225694