c# - 在已经绑定的 ListView 中显示来自数据库的列表
问题描述
澄清发生了什么。基本上我有一个 ListView 绑定,它指向一个对象中的一个 List。在同一个对象中(但不在列表中)我有另一个列表,其中包含用于下拉列表的字符串,我无法将它分配给我的列表视图,因为 DataContext 已经设置为提到的第一个列表。有人可以提供解决方案,或者更好但更有效的方法来处理这个问题吗?
看法
<ListView ItemsSource="{Binding myModel.myCollection}" Grid.Row="1" Grid.Column="0">
<ListView.View>
<GridView>
<GridViewColumn Header="Name">
<GridViewColumn.CellTemplate>
<DataTemplate>
<TextBox Text="{Binding Name, Mode=TwoWay}"></TextBox>
</DataTemplate>
</GridViewColumn.CellTemplate>
</GridViewColumn>
<GridViewColumn Header="Category Tag">
<GridViewColumn.CellTemplate>
<DataTemplate>
<ComboBox ItemsSource="{Binding myModel.CategoryList}"></ComboBox>
</DataTemplate>
</GridViewColumn.CellTemplate>
</GridViewColumn>
</GridView>
</ListView.View>
</ListView>
模型
public class SiteUrlsModel : INotifyPropertyChanged
{
public string CaseName { get; set; }
public List<string> TestList => new List<string> { "Test1", "Test2", "Test3" };
public List<string> _categoryTagList;
public List<string> CategoryTagList
{
get => _categoryTagList;
set
{
if (_categoryTagList == value)
return;
_categoryTagList = value;
OnPropertyChanged();
}
}
private ObservableCollection<SiteUrlsModel> _myCollection;
public ObservableCollection<SiteUrlsModel> myCollection
{
get => _siteurlscCollection;
set
{
if (_siteurlscCollection == value)
return;
_siteurlscCollection = value;
OnPropertyChanged();
}
}
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
}
为简单起见,我排除了 ViewModel 和 Code-Behind,但在InitialiseComponent()之后,我有DataContext = new TestViewModel()并且在我的 ViewModel 中,我有一个属性,它创建了我的模型的新实例,并添加了一个 getter 以确保一切正常无障碍。请放心,列表会被填充我只是想单独填充一个下拉列表。
解决方案
发生这种情况是因为,组合框的数据上下文将是 myModel 的项目。
您需要明确告诉组合框从它的父数据上下文中获取 itemssource。
<DataTemplate>
<ComboBox ItemsSource="{Binding DataContext.myModel.CategoryList, RelativeSource={RelativeSource AncestorType=DataGrid}}"></ComboBox>
</DataTemplate>
推荐阅读
- r - 使用 tidyverse 在 R 中对数据进行分组和嵌套会产生错误
- python - 将 lowerCamelCase 转换为 snake_case 的最佳方法
- drupal - 将带有作曲家的 drupal 8 迁移到另一台服务器
- java - Spring Data Rest 处理 AfterLinkSaveEvent
- python - 安装“node-red-contrib-zeromq”时出错
- git - 修补文件时在文件末尾拆分块
- wordpress - Wordpress/Woocommerce rest api 根据用户角色返回产品价格
- javascript - 从 Settimeout 返回 true
- java - 使用 MySqlPool quarkus 响应式客户端和 AWS IAM 访问 aurora Mysql db
- javascript - 如果用户单击不同页面中的登录按钮,您如何更改布尔值?