Home > Software engineering >  Save the data while filtering CollectionView
Save the data while filtering CollectionView

Time:07-14

I have ItemsControl that every item is CheckBox.

If I checked for an item and then performs a filter - the CheckBox is no longer checked.

What solution is there for such a case?

public ObservableCollection<string> Names { get; set; } = new() { "A", "B", "C", "D", "E", "F" };
<Grid>
    <Grid Width="150" Height="30">
        <TextBox x:Name="TextBoxSearch" PreviewKeyUp="UIElement_OnPreviewKeyUp"/>
        <Path Style="{StaticResource SearchIconStyle}" HorizontalAlignment="Right"/>
    </Grid>
    <ItemsControl x:Name="ItemsControlNames" ItemsSource="{Binding Source={StaticResource NamesKey}}">
        <ItemsControl.ItemTemplate>
            <DataTemplate>
                <StackPanel Orientation="Horizontal">
                    <CheckBox Content="{Binding}" Height="33" Padding="5"/>
                </StackPanel>
            </DataTemplate>
        </ItemsControl.ItemTemplate>
    </ItemsControl>
</Grid>
private void UIElement_OnPreviewKeyUp(object sender, KeyEventArgs e)
{
    if (ItemsControlNames?.ItemsSource is ICollectionView cView)
    {
        cView.Filter = FilterByName;
    }
}

private bool FilterByName(object item)
{
    if (item is string s)
    {
        return s.IndexOf(TextBoxSearch.Text, StringComparison.OrdinalIgnoreCase) >= 0 || string.IsNullOrWhiteSpace(TextBoxSearch.Text);
    }
    return true;
}

enter image description here

CodePudding user response:

create a new item type with Name and IsSelected properties and bind both properties.

public class SelectableItem
{
     public bool IsSelected { get; set; }
     public string Name { get; set; }
}

public ObservableCollection<SelectableItem> Names { get; set; } = new() 
{ 
     new SelectableItem { Name = "A" }, 
     ...
     new SelectableItem { Name = "F" },
};

<Grid>
    <Grid Width="150" Height="30">
        <TextBox x:Name="TextBoxSearch" PreviewKeyUp="UIElement_OnPreviewKeyUp"/>
        <Path Style="{StaticResource SearchIconStyle}" HorizontalAlignment="Right"/>
    </Grid>
    <ItemsControl x:Name="ItemsControlNames" ItemsSource="{Binding Source={StaticResource NamesKey}}">
        <ItemsControl.ItemTemplate>
            <DataTemplate>
                <StackPanel Orientation="Horizontal">
                    <CheckBox IsChecked="{Binding IsSelected}" Content="{Binding Name}" Height="33" Padding="5"/>
                </StackPanel>
            </DataTemplate>
        </ItemsControl.ItemTemplate>
    </ItemsControl>
</Grid>
  •  Tags:  
  • wpf
  • Related