繁体   English   中英

WPF命令未按预期启用按钮

[英]WPF Command not Enabling a button as expected

我用一个简单的示例模拟了场景,其中窗口旁边有一个文本框和一个按钮。 文本框上的值超过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; 
   }
}

纯粹主义者不喜欢这种模式,但是...谁关心挂断事件处理程序的所有废话呢? 底线是命令是否可以执行,无论是否建议重新查询。

暂无
暂无

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

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