I sort and group listbox items, I use CollectioView on this purpose.
From view model class I bind collection on ListBox ItemSource property, here is it.
<
The workaround isn't perfect. As I said, it is better to use ViewModels with your own grouping, but it will require much more code.
You need two event handlers:
private Dictionary expandStates = new Dictionary();
private void Grid_Loaded(object sender, RoutedEventArgs e)
{
var grid = (Grid)sender;
var dc = grid.DataContext as CollectionViewGroup;
var groupName = (string)dc.Name;
//If the dictionary contains the current group, retrieve a saved state of the group
if (this.expandStates.ContainsKey(groupName))
{
var btn = (ToggleButton)grid.FindName("btnShowHide");
btn.IsChecked = this.expandStates[groupName];
} //Else add default state
else this.expandStates.Add(groupName, true);
}
private void btnShowHide_Click(object sender, RoutedEventArgs e)
{
var btn = (ToggleButton)sender;
var dc = (CollectionViewGroup)btn.DataContext;
var groupName = (string)dc.Name;
//Loaded event is fired earlier than the Click event, so I'm sure that the dictionary contains the key
this.expandStates[groupName] = btn.IsChecked; //Save the current state
}
They are bound with controls here:
and here:
If you define Template for GroupItem somewhere in an external dictionary, you must use UserControl for the purpose of having access to code-behind.