如何将Datagrid
与两列(DataGridTextColumn
和DataGridComboBoxColumn
)绑定到ObservableCollection<Team> Teams
?
DataGridTextColumn
绑定正确。但DataGridComboBoxColumn
中没有显示任何内容。
代码隐藏
public class Team
{
public string Name { get; set; }
public List<string> Members { get; set; }
}
public class ViewModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private ObservableCollection<Team> teams = new ObservableCollection<Team>
{
new Team()
{
Name = "A", Members = new List<string> {"John", "Jack"},
},
new Team()
{
Name = "B", Members = new List<string> {"Sarah", "Anna"},
}
};
public ObservableCollection<Team> Teams
{
get { return teams; }
set
{
teams = value;
RaisePropertyChanged("Teams");
}
}
private void RaisePropertyChanged(string propertyName)
{
var handler = PropertyChanged;
if (handler == null) return;
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
XAML
<DataGrid ItemsSource="{Binding Path=Teams}"
AutoGenerateColumns="False">
<DataGrid.Columns>
<DataGridTextColumn Header="Team"
IsReadOnly="True"
Width="*"
Binding="{Binding Name}"/>
<DataGridComboBoxColumn Header="Members"
Width="*"
/>
</DataGrid.Columns>
</DataGrid>
答案 0 :(得分:2)
您需要使用ViewModel实例设置控件的save
属性。比如,在控制构造函数中
DataContext
并在XAML中填写DisplayMemberPath
this.DataContext = new ViewModel();
<强>更新强>
我是不正确的。因为<DataGridTextColumn Header="Team" DisplayMemberPath="Name" ...
不会继承DataContext,所以要按照以下方式执行操作:
DataGridComboboxColumn
答案 1 :(得分:1)
只需使用&#34; DataGridTemplateColumn&#34;。 别忘了添加一个selectedItem成员。
<DataGridTemplateColumn Header="Members">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate DataType="wpfApplication1:Team">
<ComboBox ItemsSource="{Binding Members}"/>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>