C# 无法将DataGridComboxColumn绑定到视图模型集合
我有一个包含项目集合的视图模型,每个项目都有一个键集合。我想让DataGridComboxColumn显示每个项的键的下拉列表。我见过类似的问题,但没有一个答案对我有帮助。当我运行我的应用程序时,所有的组合框都是空的。这是我的xaml:C# 无法将DataGridComboxColumn绑定到视图模型集合,c#,wpf,datagrid,C#,Wpf,Datagrid,我有一个包含项目集合的视图模型,每个项目都有一个键集合。我想让DataGridComboxColumn显示每个项的键的下拉列表。我见过类似的问题,但没有一个答案对我有帮助。当我运行我的应用程序时,所有的组合框都是空的。这是我的xaml: <Window x:Class="TestDataGridCombobox.MyWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xm
<Window
x:Class="TestDataGridCombobox.MyWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<DataGrid ItemsSource="{Binding Items}" AutoGenerateColumns="False">
<DataGrid.Columns>
<DataGridTextColumn Binding="{Binding Name}"/>
<DataGridComboBoxColumn ItemsSource="{Binding Path=Keys}" SelectedValueBinding="{Binding Path=SelectedKey}"/>
</DataGrid.Columns>
</DataGrid>
</Window>
我可以使用模板列,但我感兴趣的是为什么这个特定的示例不起作用,代码有什么问题吗?或者DataGridComboxColumn是否有任何限制
或者DataGridComboxColumn是否有任何限制
是的,有一些限制。您可以通过阅读以下内容中的备注部分找到:
要填充下拉列表,请首先使用以下选项之一设置组合框的ItemsSource属性:
静态资源。有关详细信息,请参阅。
一个x:静态代码实体。有关详细信息,请参阅。
类型的内联集合。
解决这个问题有很多变通方法,例如,正如您所写的,您可以使用
我希望它能帮助你
using System.Collections.ObjectModel;
using System.ComponentModel;
namespace TestDataGridCombobox
{
public class MyViewModel : INotifyPropertyChanged
{
public MyViewModel()
{
Items.Add(new MyItem { Name = "Item1" });
Items.Add(new MyItem { Name = "Item2" });
Items.Add(new MyItem { Name = "Item3" });
}
private ObservableCollection<MyItem> items = new ObservableCollection<MyItem>();
public ObservableCollection<MyItem> Items
{
get { return items; }
set
{
if (items == value)
return;
items = value;
OnPropertyChanged("Items");
}
}
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged(string property)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(property));
}
}
public class MyItem : INotifyPropertyChanged
{
public MyItem()
{
Keys.Add("Key1");
Keys.Add("Key2");
Keys.Add("Key3");
SelectedKey = "Key1";
}
private string name;
public string Name
{
get { return name; }
set
{
if (name == value)
return;
name = value;
OnPropertyChanged("Name");
}
}
private string selectedKey;
public string SelectedKey
{
get { return selectedKey; }
set
{
if (selectedKey == value)
return;
selectedKey = value;
OnPropertyChanged("SelectedKey");
}
}
private ObservableCollection<string> keys = new ObservableCollection<string>();
public ObservableCollection<string> Keys
{
get { return keys; }
set
{
if (keys == value)
return;
keys = value;
OnPropertyChanged("Keys");
}
}
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged(string property)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(property));
}
}
}
public partial class MyWindow : Window
{
public MyWindow()
{
InitializeComponent();
DataContext = new MyViewModel();
}
}