Reputation: 93
UWP DataGrid: link
Here is the 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}">
Bound Property:
private ObservableCollection<User> _userSource;
public ObservableCollection<User> UserSource {
get { return _userSource; }
set { SetProperty(ref _userSource, value); }
}
Method:
//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);
}
}
}
The datagrid will display 3 items for example, then I did some changes for example added new item or removed 1 item, When I click the button that calls the LoadData(), the UserSource was changed and contains the new data, But the datagrid doesn't reload or show the new/updated data, How can I reload the DataGrid via mvvm?
Upvotes: 0
Views: 689
Reputation: 93
Simplest Solution:
changed the property to IEnumerable as my AllUsers functions returns IEnumerable:
private IEnumerable<User> _userSource;
public IEnumerable<User> UserSource {
get { return _userSource; }
set { SetProperty(ref _userSource, value); }
}
Then on LoadData:
private async void LoadUserData() {
UserSource = await sqlService.AllUsers();
}
Thanks to @Clemens
Upvotes: 0
Reputation: 32785
How to reload UWP DataGrid when ItemSource is changed
Please avoid recreate new ObservableCollection
when each button click. please implement ObservableCollection object once then edit it. Please check the following code.
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);
});
}
}
}
Upvotes: 2