Sort and Group ListItems in a WPF ListBox- GroupItem collapse and expand

后端 未结 1 551
一生所求
一生所求 2020-12-20 06:53

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.

<         


        
相关标签:
1条回答
  • 2020-12-20 07:20

    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<string, bool?> expandStates = new Dictionary<string, bool?>();
    
        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:

    <ControlTemplate TargetType="{x:Type GroupItem}">
        <Grid Loaded="Grid_Loaded">
    

    and here:

    <ToggleButton x:Name="btnShowHide" Click="btnShowHide_Click" IsChecked="True" Margin="3.5" />
    

    If you define Template for GroupItem somewhere in an external dictionary, you must use UserControl for the purpose of having access to code-behind.

    0 讨论(0)
提交回复
热议问题