gpt4 book ai didi

c# - WPF 在运行期间禁用命令

转载 作者:行者123 更新时间:2023-11-30 19:01:46 25 4
gpt4 key购买 nike

我需要在它运行时禁用按钮。我有这段代码:

RelayCommand.cs 这是我的命令类。

class RelayCommand : ICommand
{
readonly Action<object> _execute;
readonly Predicate<object> _canExecute;

public RelayCommand(Action<object> execute)
: this(execute, null)
{
}

public RelayCommand(Action<object> execute, Predicate<object> canExecute)
{
if (execute == null)
{
throw new ArgumentNullException("execute");
}

_execute = execute;
_canExecute = canExecute;
}

public bool CanExecute(object parameter)
{
return _canExecute == null ? true : _canExecute(parameter);
}

public event EventHandler CanExecuteChanged
{
add { CommandManager.RequerySuggested += value; }
remove { CommandManager.RequerySuggested -= value; }
}

public void Execute(object parameter)
{
_execute(parameter);
}
}

MainWindowViewModel.cs 这是我的绑定(bind)命令。

private RelayCommand _getTextCommand;
public ICommand GetTextCommand
{
get
{
if (_getTextCommand == null)
{
_getTextCommand = new RelayCommand(
param => this.GetText(param),
param => true
);
}

return _getTextCommand;
}
}

MainWindow.xaml 这是我绑定(bind)命令的 XAML 代码。

<Button x:Name="getTextButton" Command="{Binding GetTextCommand}" CommandParameter="{Binding ElementName=textTypeSelector, Path=SelectedIndex}"/>

这是我在命令中启动的代码:

public async void GetText(object o)
{
await Task.Factory.StartNew(() =>
{
// code
});
}

最佳答案

试试这个:在 View 模型中添加一个 bool 属性并在 View 模型中实现 INotifyPropertyChanged

    private bool isEnable = true;

public bool IsEnable
{
get { return isEnable; }
set
{
isEnable = value;
NotifyPropertyChanged();
}
}

public async void GetText(object o)
{
await Task.Factory.StartNew(() =>
{

IsEnable = false;
});
IsEnable = true;
}

public event PropertyChangedEventHandler PropertyChanged;

private void NotifyPropertyChanged([CallerMemberName] String propertyName = "")
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}

将其绑定(bind)到按钮的 IsEnable 属性上

<Button x:Name="abc"
Command="{Binding GetTextCommand}"
IsEnabled="{Binding IsEnable}" />

根据需要设置 IsEnable。

关于c# - WPF 在运行期间禁用命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22373563/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com