如何解决ListView 不显示 BindingCollection 的内容
我已经查看了大约一百个不同的堆栈溢出问题/答案,我的代码看起来与大多数答案完全相同,但我仍然无法让 ListView 显示任何内容。
在我的 MainWindow.cs
中有
api = new Api();
MainViewModel = new MainViewModel();
MainViewModel.Loading = true;
DataContext = MainViewModel;
AttemptLogin();
if (Account.IsLoggedIn){
api.getAccountDetails();
MainViewModel.GetProfiles(api);
InitializeComponent();
}
我的 MainViewModel
包含:
private ObservableCollection<Profile> _profiles;
public ObservableCollection<Profile> Profiles => _profiles;
...
public void GetProfiles(Api api){
_profiles = new ObservableCollection<Profile>(api.getProfiles());
}
在我的 xaml 中,我有:
<Window.DataContext>
<viewModels:MainViewModel />
</Window.DataContext>
<ListView
ItemsSource="{Binding Profiles}">
<ListView.View>
<GridView>
<GridViewColumn
DisplayMemberBinding="{Binding Name}"
Header="Name" />
</GridView>
</ListView.View>
</ListView>
API 调用是:
public ObservableCollection<Profile> getProfiles(){
var request = new RestRequest("api/benchmarks/results",Method.POST);
var response = _restClient.Execute(request);
dynamic test = JObject.Parse(response.Content);
ObservableCollection<Profile> Profiles = new ObservableCollection<Profile>();
for (var i = 0; i < test.result.Count; i++){
Profiles.Add(new Profile(test.result[i]));
}
return Profiles;
}
我还有其他属性显示在 MainViewModel
的 xaml 中就好了。如果我在 InitializeComponent
上放置一个断点,我可以看到 MainViewModel.Profiles
包含我期望它包含的内容。
然而,我得到的只是名称标题,没有内容。
我在这里遗漏了什么?
编辑:
如果我将 OnPropertyChanged
添加到 Profile 的 setter 并相应地调整我的视图模型:
...
public ObservableCollection<Profile> Profiles{
get => _profiles;
set{
_profiles = value;
OnPropertyChanged("Profiles");
}
}
...
public void GetProfiles(Api api){
Profiles = new ObservableCollection<Profile>(api.getProfiles());
}
没有变化。
解决方法
尝试在 InitializeComponent() 方法之后设置 DataContext。还有一个建议,将 InitializeComponent() 移出 if 块。始终远离条件块,让 UI 自行加载,然后在页面/窗口加载后决定要执行或显示的内容。
这是修改后的代码,
public MainWindow()
{
InitializeComponent(); // Keep this as first statement in your View constructor
// Move below code to some private method and make a call from here.
// Just code looks simpler and clean.
InitializeViewModel();
}
private void InitializeViewModel()
{
api = new Api();
MainViewModel = new MainViewModel();
MainViewModel.Loading = true;
DataContext = MainViewModel;
AttemptLogin();
if (Account.IsLoggedIn)
{
api.getAccountDetails();
MainViewModel.GetProfiles(api);
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。