UWP DataGrid:link
这是xaml:
<controls:DataGrid x:Name="dg_Users"
AlternatingRowBackground="Gainsboro"
AutoGenerateColumns="False"
BorderThickness="1"
CanUserResizeColumns="False"
GridLinesVisibility="Horizontal"
IsReadOnly="True"
ItemsSource="{Binding UserSource, Mode=OneWay, UpdateSourceTrigger=PropertyChanged}">
绑定属性:
private ObservableCollection<User> _userSource;
public ObservableCollection<User> UserSource {
get { return _userSource; }
set { SetProperty(ref _userSource, value); }
}
方法:
//called on constructor
private async void LoadData() {
UserSource = new ObservableCollection<User>();
var users = await sqlService.AllUsers();
if(users != null) {
foreach (var item in users) {
UserSource.Add(item);
}
}
}
例如,datagrid将显示3个项目,然后我进行了一些更改,例如添加了新项目或删除了1个项目,当我单击调用LoadData()的按钮时,UserSource被更改并包含新数据,但是datagrid不会重新加载或显示新的/更新的数据,如何通过mvvm重新加载DataGrid?
答案 0 :(得分:1)
更改ItemSource后如何重新加载UWP DataGrid
请避免在每次单击按钮时重新创建新的ObservableCollection
。请实现一次ObservableCollection对象,然后对其进行编辑。请检查以下代码。
public class MainPageViewModel
{
public ObservableCollection<User> UserSource { get; } = new ObservableCollection<User>();
public MainPageViewModel()
{
LoadData();
}
private async void LoadData()
{
UserSource.Clear();
var users = await sqlService.AllUsers();
if (users != null)
{
foreach (var item in users)
{
UserSource.Add(item);
}
}
}
public ICommand BtnClickCommand
{
get
{
return new RelayCommand(() =>
{
UserSource.RemoveAt(0);
});
}
}
}
答案 1 :(得分:0)
最简单的解决方案:
将属性更改为IEnumerable,因为我的AllUsers函数返回IEnumerable:
private IEnumerable<User> _userSource;
public IEnumerable<User> UserSource {
get { return _userSource; }
set { SetProperty(ref _userSource, value); }
}
然后在LoadData上
private async void LoadUserData() {
UserSource = await sqlService.AllUsers();
}
感谢@Clemens