简体   繁体   English

启用DelegateCommand

[英]Enable DelegateCommand

Little puzzled 有点不解

If i have a button in a wpf window and bind it to a DelegateCommand 如果我在wpf窗口中有一个按钮并将其绑定到DelegateCommand

<Button Grid.Row="1"  Content="Remove" Command="{Binding CommandDelete }" />

And in my simple viewmodel i attach 在我简单的视图模型中

CommandDelete = new DelegateCommand<string>(OnDeleteExecute, OnDeleteCanExecute);

If the button is to be enabled when i choose an item from a list i can bind the list selecteditem to property in my viewmodel 如果从列表中选择一个项目时要启用按钮,则可以将列表中的selecteditem绑定到视图模型中的属性

Report selectedReport;
            public Report SelectedReport
            {
                get { return this.selectedReport ;}
                set { this.selectedReport = value;}
            }
private bool OnDeleteCanExecute(string commandParameter)
            {
                return (this.selectedReport != null);
            }

This seems fine to me so far and the only thing missing is to raise a CanExecute event for the specific button in the setter for SelectedReport 到目前为止,这对我来说似乎还不错,唯一缺少的是为SetterReport的设置器中的特定按钮引发CanExecute事件

CommandDelete.RaiseCanExecuteChanged();

This works but my question is if i have 10 button do i need to call RaiseCanExecuteChanged for each and every button each time a item is selected or is there as smarter way 这是可行的,但我的问题是,如果我有10个按钮,那么每次选择一个项目时,是否需要为每个按钮调用RaiseCanExecuteChanged?

Usually I place my RaiseCanExecuteChanged() in the PropertyChanged event for that class. 通常,我将RaiseCanExecuteChanged()放在该类的PropertyChanged事件中。

For example, if DeleteCommand.CanExecute is based on the SelectedReport property, I'll hook into the PropertyChanged event of the ViewModel and raise the CanExecuteChanged event anytime SelectedReport changes. 例如,如果DeleteCommand.CanExecute基于SelectedReport属性,则我将钩接到ViewModelPropertyChanged事件中,并在SelectedReport发生更改时引发CanExecuteChanged事件。

void MyViewModel_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
    if (e.PropertyName == "SelectedReport")
        DeleteCommand.RaiseCanExecuteChanged();
}

This keeps all the logic in one central place and ensures the CanExecuteChanged gets raised whenever one of the parameters changes. 这将所有逻辑都放在一个中央位置,并确保只要其中一个参数发生更改, CanExecuteChanged就会引发。

The other alternative is to switch from using a DelegateCommand to a RelayCommand , which automatically raise it's CanExecuteChanged when a property changes. 另一种选择是从使用DelegateCommand切换到RelayCommand ,当属性更改时,它会自动引发其CanExecuteChanged I would assume there's a performance difference, however have never noticed one. 我以为会有性能差异,但是从来没有注意到。

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

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