我有一个 Roles
的列表我想在 DataGrid
中选择细胞 ComboBox
.
我有 ObservableCollection
Roles
对于ComboBox
在 ViewModel 中填充。
出于某种原因,ComboBox
中没有显示任何内容尽管。附加此对象集合的正确方法是什么?
任何意见或建议都会有所帮助。
人物型号:
public int SelectedRole { get; set; }
榜样:public int Id { get; set; }
public int Role { get; set; }
public string Description { get; set; }
public string RoleInfo
{
get
{
return $"{Role} - {Description}";
}
}
查看型号:private ObservableCollection<PersonModel> _people;
public ObservableCollection<PersonModel> People
{
get { return _people; }
set
{
_people = value;
NotifyOfPropertyChange(() => People);
}
}
public ObservableCollection<RoleModel> _roles;
public ObservableCollection<RoleModel> Roles
{
get
{
return _roles;
}
set
{
_roles = value;
NotifyOfPropertyChange(() => Roles);
}
}
public PersonViewModel(IEventAggregator events, IWindowManager windowmanager)
{
_events = events;
_windowManager = windowmanager;
sql = "SELECT * FROM People";
People = SqliteConnector.LoadData<PersonModel>(sql, new Dictionary<string, object>());
sql = "SELECT * FROM Roles";
Roles = SqliteConnector.LoadData<PersonModel>(sql, new Dictionary<string, object>());
}
查看:<DataGrid ItemsSource="{Binding Path=People}"
AutoGenerateColumns="False"
CanUserDeleteRows="True"
CanUserReorderColumns="True"
CanUserAddRows="True"
AlternatingRowBackground="#dfdfdf"
cm:Message.Attach="[Event RowEditEnding] = [Action SaveOrUpdate()]">
<DataGridTemplateColumn Header="Type">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<TextBlock Text="{Binding Path=Role}"/>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
<DataGridTemplateColumn.CellEditingTemplate>
<DataTemplate>
<ComboBox DisplayMemberPath="RoleInfo"
ItemsSource="{Binding Path=Roles}"
SelectedValue="{Binding Path=SelectedRole, UpdateSourceTrigger=PropertyChanged}"
SelectedValuePath="Role" />
</DataTemplate>
</DataGridTemplateColumn.CellEditingTemplate>
</DataGridTemplateColumn>
</DataGrid>
最佳答案
DataGrid 的“行”元素的 DataContext 是 ItemsSource 集合的对应项,即 PersonModel 实例 - 它当然没有 Roles
属性(property)。您应该已经在 Visual Studio 的输出窗口中观察到相应的数据绑定(bind)错误消息。
为了绑定(bind)到父 View 模型的 Roles 属性,使用如下表达式:
ItemsSource="{Binding DataContext.Roles,
RelativeSource={RelativeSource AncestorType=DataGrid}}"
SelectedValue 绑定(bind)可以简单地如下所示,因为 PropertyChanged
已经是默认 UpdateSourceTrigger
对于那个属性。SelectedValue="{Binding Path=SelectedRole}"
关于C# WPF MVVM ItemSource 未附加列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63079969/