繁体   English   中英

在WPF / MVVM中,如何以完美的方式实现“全选”功能

[英]In WPF/MVVM, how to implement the “Select All” function in a perfect way

在View中,即XAML,我已将SelectAll bool值绑定到Checkbox控件

<CheckBox Grid.Row="5" Content="Select All" HorizontalAlignment="Left" Margin="0,5, 0, 0"  IsChecked="{Binding Path=SelectAll, Mode=TwoWay}" Width="206"></CheckBox>

并将SelectAll填充为

public bool SelectAll
    {
        get { return this.Get<bool>("SelectAll"); }
        set 
        {
            this.Set<bool>("SelectAll", value);
            if (this.SelectAllCommand.CanExecute(null))
                this.SelectAllCommand.Execute(value);
        }
    }

是的,它看起来不错,但我有一个问题......

当手动选中所有复选框时,应自动选择selectall复选框...那时,我们不希望执行SelectAllCommand命令...

我怎么能这样做.....我知道也许这是一件容易的工作,但如何完美地完成....

谢谢你提前给我一些建议

尝试

public bool? SelectedAll
{
    get { return this.Get<bool?>("SelectedAll"); }
    set 
    {
        if(Equals(SelectedAll, value) == true)
            return;
        this.Set<bool?>("SelectedAll", value);
        OnSelectedAllChanged(value);
    }
}

private void SelectedAllChanged(bool? input)
{
    //Stuff
}

您需要使用项目的PropertyChanged事件在选择项目时重新评估SelectAll值。

例如,

// Setup PropertyChange notification for each item in collection
foreach(var item in MyCollection)
{
    item.PropertyChanged += Item_PropertyChanged;
}

private bool _isSelectAllExecuting = false;

// If the IsSelected property of an item changes, raise a property change 
// notification for SelectAll
void Item_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
    if (!_isSelectAllExecuting && e.PropertyName == "IsSelected") 
        ReevaluateSelectAll();
}

void ReevaluateSelectAll()
{
    // Will evaluate true if no items are found that are not Selected
    _selectAll = MyCollection.FirstOrDefault(p => !p.IsSelected) == null;

    // Since we're setting private field instead of public one to avoid
    // executing command in setter, we need to manually raise the
    // PropertyChanged event to notify the UI it's been changed
    RaisePropertyChanged("SelectAll");
}

void SelectAll()
{
    _isSelectAllExecuting = true;

    foreach(var item in MyCollection)
        item.IsSelected = true;

    _isSelectAllExecuting = false;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM