I have an UWP project c# where I declare an ObservableCollection of items, on the page there is a TreeView bound to the collection. When I load it everything is fine and the TreeView is populated.
I've then added a button to sort ascending and descending BUT when I sort it the TreeView is not changed; I've read a lot of similar questions but was not able to find a solution.
In one of them the solution was:
public ObservableCollection<MTreeViewPaz> Patients { get; private set; } = new ObservableCollection<MTreeViewPaz>();
... in the AppBar code behind on the AppBarToggleButton_Checked:
Patients = new ObservableCollection<MTreeViewPaz>(
from i in Patients orderby i.Data descending, i.Cognome, i.Nome select i);
The View is bind to Patients:
<winui:TreeView
x:Name="treeView"
Grid.Row="1"
Expanding="treeView_Expanding"
ItemInvoked="OnItemInvoked"
ItemTemplate="{StaticResource ItemTemplate}"
ItemsSource="{x:Bind Patients}"
SelectionMode="Single" />
But nothing happens. I've checked with the debugger and the Patients items are different before and after the sorting. So that part works fine, only is not shown.
Even it should be useless as ObservableCollection should rise events I've even tried to do this:
private ObservableCollection<MTreeViewPaz> _Patients;
public ObservableCollection<MTreeViewPaz> Patients
{
get { return _Patients; }
private set { Set(ref _Patients, value); }
}
private void Set<T>(ref T storage, T value, [CallerMemberName]string propertyName = null)
{
if (Equals(storage, value))
{
return;
}
storage = value;
OnPropertyChanged(propertyName);
}
private void OnPropertyChanged(string propertyName) => PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
But it does not work
Sorting of ObservableCollection does not change TreeView
For checking above code, I found you used default x:Bind
mode(one time). And it will not response the Patients
reset. please edit above to OneWay
Mode.
ItemsSource="{x:Bind DataSource, Mode=OneWay}"