【问题标题】:Why WPF button's command's CanExecute method is not called even if I call CommandManager.InvalidateRequerySuggested()?为什么即使我调用 CommandManager.InvalidateRequerySuggested() 也不调用 WPF 按钮命令的 CanExecute 方法?
【发布时间】:2015-11-13 00:22:15
【问题描述】:

我面临着这些问题中报告的相同问题:

Button Command CanExecute not called when property changed

How can I force a textbox change to enable my command in WPF?

(简而言之:我的命令链接按钮在应该启用时没有启用)但略有不同:我已经尝试调用 CommandManager.InvalidateRequerySuggested(),使用没有结果

最奇怪的是,只有当我“触发”窗口上的任何事件时,按钮才会启用,例如在窗口的任何点上用鼠标单击。

这里是重现问题的代码:

<Window x:Class="WpfApplication1.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:local="clr-namespace:WpfApplication1"
    mc:Ignorable="d"
    Title="MainWindow" Height="350" Width="525">
<Window.CommandBindings>
    <CommandBinding Command="{x:Static local:Commands.RunTask}" x:Name="cmdRunTask" CanExecute="CanExecuteRunTask" Executed="ExecuteRunTask">    </CommandBinding>
    <CommandBinding Command="{x:Static local:Commands.PushButton}" x:Name="cmdPushButton" CanExecute="CanPushButton" Executed="PushButton"></CommandBinding>
</Window.CommandBindings>
<StackPanel>
    <Button Content="Run task"
                x:Name="runButton"
                Command="{x:Static local:Commands.RunTask}"
                >
    </Button>
    <ProgressBar x:Name="progress"
                     Value="{Binding Path=Value, Mode=OneWay}"
                 Height="30"
                     >
    </ProgressBar>
    <Button Content="Press me if you dare"
                x:Name="pushButton"
                Command="{x:Static local:Commands.PushButton}"
                >
    </Button>
</StackPanel>

using System;
using System.ComponentModel;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;

namespace WpfApplication1
{
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            DataContext = new Model();
            ((Model)DataContext).PropertyChanged += DataContext_PropertyChanged;
            InitializeComponent();
        }

        private void DataContext_PropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            switch (e.PropertyName)
            {
                case "Ready":
                    CommandManager.InvalidateRequerySuggested();
                    break;
            }
        }

        void CanExecuteRunTask(object sender, CanExecuteRoutedEventArgs e)
        {
            e.CanExecute = true;
        }

        void ExecuteRunTask(object sender, ExecutedRoutedEventArgs e)
        {
            ((Model)DataContext).RunLongTask();
        }

        void CanPushButton(object sender, CanExecuteRoutedEventArgs e)
        {
            e.CanExecute = ((Model)DataContext).Ready;
        }

        void PushButton(object sender, ExecutedRoutedEventArgs e) { }
    }

    public static class Commands
    {
        public static readonly RoutedUICommand RunTask = new     RoutedUICommand();
        public static readonly RoutedUICommand PushButton = new     RoutedUICommand();
    }

    public class Model : INotifyPropertyChanged
    {
        private bool _ready = false;
        public bool Ready
        {
            get { return _ready; }
            set
            {
                _ready = value;
                RaisePropertyChanged("Ready");
            }
        }

        private int _value = 0;
        public int Value
        {
            get { return _value; }
            set
            {
                _value = value;
                RaisePropertyChanged("Value");
            }
        }

        public async void RunLongTask()
        {
            await RunLongTaskAsync();   
        }
        private Task RunLongTaskAsync()
        {
            this.Ready = false;
            Task t = new Task(() => {
                for (int i = 0; i <= 100; i++)
                {
                    Value = i;
                    System.Threading.Thread.Sleep(20);
                }
                this.Ready = true;
            });
            t.Start();
            return t;
        }

        public event PropertyChangedEventHandler PropertyChanged;
        protected void RaisePropertyChanged(string propertyName)
        {
            if (PropertyChanged != null)
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}

【问题讨论】:

  • 嗨安东尼,我想你的意思是标题不清楚,我希望现在更好。谢谢。
  • Leo,不,我的意思是请阅读有关如何提问的指南。这不是博客。您不会用答案添加到您的问题中。你不添加笑脸。如果没有实际代码进行测试,您不会发布问题。将其视为更多的历史文件。您尽可能详细地说明您的问题,然后有人会解决它。然后,将来它可以用来回答同样的问题。这整件事的格式是错误的。
  • 我会按照你的要求整合,但实际上我并不完全同意你的看法,因为问题添加表单允许你在问题的同时直接插入答案,正是因为您只是想分享一个您发现的解决自己问题的解决方案,而无需实际寻求帮助,而只是分享一个很难找到的解决方案。正如这里实际建议的那样:blog.stackoverflow.com/2011/07/… 无论如何,我会按照您的正确建议添加一些代码进行测试。
  • 嗨 Anthony,你说得对,现在看起来好多了。再次感谢和抱歉。

标签: wpf


【解决方案1】:

虽然“PropertyChanged”事件会自动编组,但不会调用 CommandManager.InvalidateRequerySuggested()。

因此,要解决此问题,只需确保在 Dispatcher 线程上进行调用,如下所示:

    private void DataContext_PropertyChanged(object sender, PropertyChangedEventArgs e)
    {
        switch (e.PropertyName)
        {
            case "Ready":
                var d = Application.Current.Dispatcher;
                if (d.CheckAccess())
                    CommandManager.InvalidateRequerySuggested();
                else
                    d.BeginInvoke((Action)(() => { CommandManager.InvalidateRequerySuggested(); }));
                break;
        }
    }

在依赖由异步任务触发的属性更改时要小心。

我希望这可以帮助你们中的一些人节省一些工作时间...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-01-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-15
    相关资源
    最近更新 更多