C#:在搜索/计算过程中禁用按钮
我有一个搜索对话框,我想在搜索过程中禁用搜索按钮。 这是当前代码,但按钮不会被取消激活
视图:
视图模型:
private bool _isNotSearching; public bool IsNotSearching { get { return _isNotSearching; } set { _isNotSearching = value; OnPropertyChanged("IsNotSearching"); } } private RelayCommand _startSearchCommand; public ICommand StartSearchCommand { get { if (_startSearchCommand == null) _startSearchCommand = new RelayCommand(p => ExecuteSearch()); return _startSearchCommand; } } private void ExecuteSearch() { IsNotSearching = false; //do some searching here IsNotSearching = true; }
我出于这个原因制作了AsyncDelegateCommand
(基于着名的DelegateCommand
),它在执行命令操作期间在内部禁用命令(在UI中):
public class AsyncDelegateCommand : ICommand { readonly Action
XAML:
视图模型:
AsyncDelegateCommand SomeCommand { get; } // in constructor SomeCommand = new AsyncDelegateCommand(o => { Thread.Sleep(5000); }); // code to run
点击并禁用它时我不确定外观 – 它可能看起来相同。
但是网络是正确的。 如果在主UI线程中执行逻辑,则UI可能会被冻结,直到执行结束(并且不会更改或更改为快速)。
尝试将您的逻辑放入调度员 。 就像代码的下一部分一样。
Application.Current.Dispatcher.BeginInvoke( DispatcherPriority.Background, new Action(() => { //do some searching here }));
顺便说一句,我在那里拿了这个代码。
编辑:不要将此用于您的解决方案。 这是错误的(检查评论)。
需要更新可视元素异步时使用调度程序。
Application.Current.Dispatcher.BeginInvoke( DispatcherPriority.Background, new Action(() => { textbox.Content = "some result"; }));
你可以试试命令可以执行以禁用命令而不添加IsEnabled
属性
private RelayCommand _startSearchCommand; public RelayCommand StartSearchCommand { get { return _startSearchCommand?? (_startSearchCommand= //Added can execute command , only execute if system is not busy at the moment. new RelayCommand(async () => await OnExecuteSearch(), () => !IsBusy)); } }
命令处理程序
internal async Task OnExecuteSearch() { IsBusy = true; //Execute your action //and finally IsBusy = false; }
XAML
Relay Command中的canexecute
将为您控制IsEnabled
属性。
这段代码必须有效。
private async void ExecuteSearch() { IsNotSearching = false; var task = Task.Factory.StartNew(() => { //do some searching here }); await task; IsNotSearching = true; }