WPF 命令未按预期启用按钮
本文关键字:启用 按钮 命令 WPF | 更新日期: 2023-09-27 18:33:54
我用一个简单的例子模拟了这个场景,其中窗口有一个文本框,旁边有一个 buton。文本框上的值超过 10000 后,按钮将被激活。但是该按钮未启用。
<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="150" Width="225">
<Grid>
<WrapPanel>
<TextBox Text="{Binding X}" Width="100"/>
<Button Command="{Binding ButtonCommand}" CommandParameter="{Binding}" Width="100"/>
</WrapPanel>
</Grid>
public partial class MainWindow : Window
{
private ViewModel vm = new ViewModel();
public MainWindow()
{
InitializeComponent();
this.DataContext = vm;
}
protected override void OnContentRendered(EventArgs e)
{
Task.Run(new Action(() =>
{
int c = 0;
while (true)
{
vm.X = c++;
}
}));
base.OnContentRendered(e);
}
}
public class ViewModel : INotifyPropertyChanged
{
int x;
public int X
{
get { return x; }
set
{
if (x != value)
{
x = value;
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs("X"));
}
}
}
}
ICommand c = new MyCommand();
public ICommand ButtonCommand
{
get
{
return c;
}
}
public event PropertyChangedEventHandler PropertyChanged;
}
public class MyCommand : ICommand
{
public bool CanExecute(object parameter)
{
if (parameter != null && (parameter as ViewModel).X > 10000)
{
return true;
}
return false;
}
public event EventHandler CanExecuteChanged
{
add
{
CommandManager.RequerySuggested += value;
}
remove
{
CommandManager.RequerySuggested -= value;
}
}
public void Execute(object parameter)
{
throw new NotImplementedException();
}
}
您需要具备以下条件...
while (true)
{
vm.X = c++;
CommandManager.InvalidateRequerySuggested();
}
您必须在期望 CanExecute 方法的任何时间点引发事件 CanExecuteChanged输出将更改
因此,例如您可以添加
CanExecuteChanged ();
vm.X = c++;
这是实现 ICommand 的简单方法
public class MyCommand : ICommand
{
private bool _CanExecute = true;
public bool CanExecute(object parameter)
{
return _CanExecute;
}
public void Execute(object parameter)
{
if(parameter!=null){
_CanExecute = false;
//do your thing here....
_CanExecute = true;
}
}
纯粹主义者不会喜欢这种模式,但是...谁在乎连接拆除事件处理程序的所有废话? 底线是命令可以执行或不执行,无论建议的重新查询如何。