【问题标题】:Why is CanExecute invoked after the command source is removed from the UI?为什么从 UI 中删除命令源后调用 CanExecute?
【发布时间】:2012-04-23 12:41:20
【问题描述】:

我试图了解为什么在已从 UI 中删除的命令源上调用 CanExecute。这是一个简化的程序来演示:

<Window x:Class="WpfApplication1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Height="350" Width="525">
    <StackPanel>
        <ListBox ItemsSource="{Binding Items}">
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <StackPanel>
                        <Button Content="{Binding Txt}" 
                                Command="{Binding Act}" />
                    </StackPanel>
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>
        <Button Content="Remove first item" Click="Button_Click"  />
    </StackPanel>
</Window>

代码隐藏:

public partial class MainWindow : Window
{
    public class Foo
    {
        static int _seq = 0;
        int _txt = _seq++;
        RelayCommand _act;
        public bool Removed = false;

        public string Txt { get { return _txt.ToString(); } }

        public ICommand Act
        {
            get
            {
                if (_act == null) {
                    _act = new RelayCommand(
                        param => { },
                        param => {
                            if (Removed)
                                Console.WriteLine("Why is this happening?");
                            return true;
                        });
                }
                return _act;
            }
        }
    }

    public ObservableCollection<Foo> Items { get; set; }

    public MainWindow()
    {
        Items = new ObservableCollection<Foo>();
        Items.Add(new Foo());
        Items.Add(new Foo());
        Items.CollectionChanged += 
            new NotifyCollectionChangedEventHandler(Items_CollectionChanged);
        DataContext = this;
        InitializeComponent();
    }

    void Items_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
    {
        if (e.Action == NotifyCollectionChangedAction.Remove)
            foreach (Foo foo in e.OldItems) {
                foo.Removed = true;
                Console.WriteLine("Removed item marked 'Removed'");
            }
    }

    void Button_Click(object sender, RoutedEventArgs e)
    {
        Items.RemoveAt(0);
        Console.WriteLine("Item removed");
    }
}

当我单击“删除第一项”按钮时,我得到以下输出:

Removed item marked 'Removed'
Item removed
Why is this happening?
Why is this happening?

“为什么会这样?”每次我点击窗口的某个空白部分时都会打印出来。

为什么会这样?我可以或应该做些什么来防止 CanExecute 在已删除的命令源上被调用?

注意: RelayCommand 可以在here找到。

对 Michael Edenfield 问题的回答:

Q1: CanExecute 被移除按钮调用时的调用栈:

WpfApplication1.exe!WpfApplication1.MainWindow.Foo.get_Act.AnonymousMethod__1(object param) 第 30 行 WpfApplication1.exe!WpfApplication1.RelayCommand.CanExecute(object parameter) 第 41 行 + 0x1a 字节 PresentationFramework.dll!MS.Internal.Commands.CommandHelpers.CanExecuteCommandSource(System.Windows.Input.ICommandSource commandSource) + 0x8a 字节 PresentationFramework.dll!System.Windows.Controls.Primitives.ButtonBase.UpdateCanExecute() + 0x18 字节 PresentationFramework.dll!System.Windows.Controls.Primitives.ButtonBase.OnCanExecuteChanged(object sender, System.EventArgs e) + 0x5 字节 PresentationCore.dll!System.Windows.Input.CommandManager.CallWeakReferenceHandlers(System.Collections.Generic.List handlers) + 0xac 字节 PresentationCore.dll!System.Windows.Input.CommandManager.RaiseRequerySuggested(object obj) + 0xf 字节

Q2:另外,如果您从列表中删除所有按钮(不仅仅是第一个?),这种情况还会继续发生吗?

是的。

【问题讨论】:

  • 我想念 RelayCommand。这是什么?
  • 我添加了一个 RelayCommand 实现的链接。
  • 您是否尝试过在事件期间检查调用堆栈并查看是什么触发了它?此外,如果您从列表中删除 所有 按钮(不仅仅是第一个?),这种情况是否会继续发生?
  • @MichaelEdenfield:我更新了答案。

标签: c# .net wpf binding mvvm


【解决方案1】:

问题是命令源(即按钮)不会取消订阅它所绑定的命令的CanExecuteChanged,因此每当CommandManager.RequerySuggested 触发时,CanExecute 也会触发,在命令源之后很久没了。

为了解决这个问题,我在RelayCommand 上实现了IDisposable,并添加了必要的代码,这样每当模型对象被移除,以及从 UI 中移除时,都会调用 Dispose() 在其所有RelayCommand

这是修改后的RelayCommand(原为here):

public class RelayCommand : ICommand, IDisposable
{
    #region Fields

    List<EventHandler> _canExecuteSubscribers = new List<EventHandler>();
    readonly Action<object> _execute;
    readonly Predicate<object> _canExecute;

    #endregion // Fields

    #region Constructors

    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;
    }

    #endregion // Constructors

    #region ICommand

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

    public event EventHandler CanExecuteChanged
    {
        add
        {
            CommandManager.RequerySuggested += value;
            _canExecuteSubscribers.Add(value);
        }
        remove
        {
            CommandManager.RequerySuggested -= value;
            _canExecuteSubscribers.Remove(value);
        }
    }

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

    #endregion // ICommand

    #region IDisposable

    public void Dispose()
    {
        _canExecuteSubscribers.ForEach(h => CanExecuteChanged -= h);
        _canExecuteSubscribers.Clear();
    }

    #endregion // IDisposable
}

无论我在哪里使用上述内容,我都会跟踪所有实例化的 RelayCommand,以便在时机成熟时调用 Dispose()

Dictionary<string, RelayCommand> _relayCommands 
    = new Dictionary<string, RelayCommand>();

public ICommand SomeCmd
{
    get
    {
        RelayCommand command;
        string commandName = "SomeCmd";
        if (_relayCommands.TryGetValue(commandName, out command))
            return command;
        command = new RelayCommand(
            param => {},
            param => true);
        return _relayCommands[commandName] = command;
    }
}

void Dispose()
{
    foreach (string commandName in _relayCommands.Keys)
        _relayCommands[commandName].Dispose();
    _relayCommands.Clear();
}

【讨论】:

    【解决方案2】:

    使用 lambda 表达式和您似乎正在触发的事件存在一个已知问题。我不愿称其为“错误”,因为我对内部细节的了解不足以知道这是否是预期的行为,但这对我来说似乎违反直觉。

    这里的关键指示是调用堆栈的这一部分:

    PresentationCore.dll!System.Windows.Input.CommandManager.CallWeakReferenceHandlers(
       System.Collections.Generic.List handlers) + 0xac bytes 
    

    “弱”事件是一种连接不保持目标对象存活的事件的方法;之所以在这里使用它,是因为您将一个 Lamba 表达式作为事件处理程序传递,因此包含该方法的“对象”是一个内部生成的匿名对象。问题是传递给您的事件的add 处理程序的对象与传递给remove 事件的表达式的实例不同,它只是一个功能相同的对象,所以它不是取消订阅您的活动。

    如以下问题所述,有多种解决方法:

    Weak event handler model for use with lambdas

    UnHooking Events with Lambdas in C#

    Can using lambdas as event handlers cause a memory leak?

    对于您的情况,最简单的方法是将您的 CanExecute 和 Execute 代码移动到实际方法中:

    if (_act == null) {
      _act = new RelayCommand(this.DoCommand, this.CanDoCommand);
    }
    
    private void DoCommand(object parameter)
    {
    }
    
    private bool CanDoCommand(object parameter)
    {
        if (Removed)
          Console.WriteLine("Why is this happening?");
        return true;
    }
    

    或者,如果您可以安排您的对象从 lambda 构造一次 Action&lt;&gt;Func&lt;&gt; 委托,将它们存储在变量中,并在创建 RelayCommand 时使用它们,它将强制使用相同的实例. IMO,对于您的情况,这可能比它需要的更复杂。

    【讨论】:

    • 创建非匿名方法并将它们作为 RelayCommand 的构造函数的参数传递不会改变任何东西。我做了一些研究,似乎问题在于命令源(按钮)仍然订阅 CanExecuteChanged(即按钮自动挂钩到事件,但不会取消订阅。
    猜你喜欢
    • 2018-04-12
    • 2016-04-14
    • 1970-01-01
    • 1970-01-01
    • 2014-08-09
    • 2020-05-13
    • 1970-01-01
    • 1970-01-01
    • 2021-07-17
    相关资源
    最近更新 更多