I have a dropdown with three filter options: All, Active, and Inactive. Changing the selected value raises an event that adjusts the observable collection property ProjectDbUsers
in the ViewModel, which a Datagrid showing application users is bound to.
The code successfully changes the ProjectDbUsers
property when I debug, but the Datagrid is not refreshing/updating to match the changed object collection.
Note: I'm using the CommunityToolkit.WinUI.Controls.DataGrid
package in the main UI project and the CommunityToolkit.Mvvm
package in the business layer project that contains the ViewModel.
The code:
In the Manage Users page XAML, showing the Combobox and Datagrid:
<ComboBox x:Name="BasicUserFilter" Grid.Row="0" Grid.Column="1"
Height="30" Width="Auto" Margin="20,10,10,10"
ItemsSource="{x:Bind ViewModel.Filters, Mode=OneWay}"
SelectedItem="{x:Bind ViewModel.SelectedFilter, Mode=TwoWay}"
SelectionChanged="BasicUserFilter_SelectionChanged"/>
<controls:DataGrid x:Name="dataGrid1" Grid.Row="2"
Height="600" Margin="12"
AutoGenerateColumns="False"
ItemsSource="{x:Bind ViewModel.ProjectDbUsers, Mode=OneWay}">
<controls:DataGrid.Columns>
<controls:DataGridTextColumn
Header="Name"
Width="250"
Binding="{Binding UserAddisplayName}"
FontSize="14" />
...
</controls:DataGrid.Columns>
</controls:DataGrid>
The code behind where the BasicUserFilter_SelectionChanged
event fires when changing the filter Combobox value.
private void BasicUserFilter_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
ViewModel.UpdateGridBasedOnFilter();
}
Excerpts from the ViewModel class, showing the bound property definitions and the method called when the filter dropdown selection has changed:
[ObservableProperty]
private string _selectedFilter;
public ObservableCollection<string> Filters { get; } = new ObservableCollection<string>(new List<string>() { "All", "Active", "Inactive" });
public ObservableCollection<UserAd> ProjectDbUsers { get; private set; }
public void UpdateGridBasedOnFilter()
{
using (UnitOfWorkDbGlobal unitOfWorkDbGlobal = new(new MyDBContext()))
{
List<UserAd> users = new();
switch (SelectedFilter)
{
case "All":
users = unitOfWorkDbGlobal.UserAds.GetAllUsers().ToList();
break;
case "Active":
users = unitOfWorkDbGlobal.UserAds.GetAllActiveUsers().ToList();
break;
case "Inactive":
users = unitOfWorkDbGlobal.UserAds.GetAllInactiveUsers().ToList();
break;
}
ProjectDbUsers = new ObservableCollection<UserAd>(users);
}
}
What might be missing in order to allow the Datagrid to update when the ProjectDbUsers
changes?
Since you are reinstantiating the projectDbUsers property itself, you need to make it ObservableProperty.
Not directly related to your question, but instead of calling
BasicUserFilter_SelectionChanged()
in code-behind, you can usepartial
methods generated by the CommunityToolkit.Mvvm.See this sample code.
MainPage.xaml