WPF, C# - SelectAll in CheckEdit

本文关键字:in CheckEdit SelectAll WPF | 更新日期: 2023-09-27 18:08:30

如何使CheckEdit全选。

Xaml自动生成checkEdit

   <ItemsControl ItemsSource="{Binding MyProperty, Mode=TwoWay}" Margin="0"  Grid.Column="1" Grid.RowSpan="1" x:Name="MyCheck" >
        <ItemsControl.ItemTemplate>
            <DataTemplate>
                <dxe:CheckEdit Content="{Binding FilePath, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" Padding="2.5" Margin="3"  
                               IsChecked="{Binding IsChecked, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" />
            </DataTemplate>
        </ItemsControl.ItemTemplate>
        <ItemsControl.ItemsPanel>
            <ItemsPanelTemplate>
                <WrapPanel Orientation="Vertical"  />
            </ItemsPanelTemplate>
        </ItemsControl.ItemsPanel>
    </ItemsControl>
        <Button x:Name="filtrButton" Content="Filtr" Command="{Binding FiltrCommand}"  Padding="5" Margin="3" IsEnabled="{Binding IsEnabled}"/>
        <dxe:CheckEdit x:Name="CheckALL" Content="Select All" Padding="2.5" Margin="3" IsChecked="{Binding AllSelected}" />
c#

        private bool? _allSelected = true;
    public bool? AllSelected
    {
        get { return _allSelected; }
        set
        {
            _allSelected = value;
          MyProperty.ForEach(x => x.IsChecked = value);
            OnPropertyChange("AllSelected");
        }
    }
    public List<MyCheckBox> MyProperty
    {
        get { return TempList; }
        set
        {
            TempList = value;
            OnPropertyChange("MyProperty");
        }
    }
/// добавление название файла и его select
        public ViewModel(){
       TempList = new List<MyCheckBox>();
        foreach (var type in tempUniqueList)
        {
            TempList.Add(new MyCheckBox(type, _allSelected));
        }
        MyProperty = TempList;
    }

WPF, C# - SelectAll in CheckEdit

_allSelected是不必要的,因为它的状态来自于其他项是否被选中。

(注意:这是不同的选择,这意味着其他的东西在ItemsControls)
public bool? AllSelected
{
    get 
    { 
        // Check if all are checked
        if (!MyProperty.Any(x => !x.IsChecked))
        {
            return true;
        }
        // Check if none are checked
        if (!MyProperty.Any(x => x.IsChecked))
        {
            return false;
        }
        // Otherwise some are checked.
        return null;
    }
    set
    {
        _allSelected = value;
        MyProperty.ForEach(x => x.IsChecked = value);
        OnPropertyChange("AllSelected");
    }
}

现在,另一个重要的事情是,你需要引发OnPropertyChanged("AllSelected")每当其中一个项目的IsChecked()值被改变。这不是一个很好的解决方案。你需要为插入到"MyProperty"中的每一项挂接PropertyChanged事件,测试它是否为IsChecked属性,如果是则引发PropertyChanged.

就我个人而言,我倾向于认为这类事情更多地是视图的一部分,而不是视图模型。我的意思是,从概念上讲,"全选/不选"复选框实际上是ItemsControl的扩展。因此,您可能完全有理由在代码后面执行此操作,并且只需连接到DataTemplate中的Checked()事件。