我用一个简单的例子模拟了场景,其中窗口有一个文本框,旁边有一个按钮。
>此按钮在文本框上的值超过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();
}
}
答案 0 :(得分:1)
您需要拥有以下内容......
while (true)
{
vm.X = c++;
CommandManager.InvalidateRequerySuggested();
}
答案 1 :(得分:0)
您必须在您期望CanExecute方法的任何时刻引发事件CanExecuteChanged 输出将被更改
所以例如你可以添加
CanExecuteChanged ();
vm.X = c++;
答案 2 :(得分:0)
这是实现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;
}
}
纯粹主义者不会喜欢这种模式,但是......谁在乎所有与非撕裂的事件处理程序挂钩的感觉呢?底线是命令可以执行与否,无论重新查询建议。