7

我试图了解为什么在已从 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 。

迈克尔·伊登菲尔德问题的答案:

Q1:删除按钮时调用 CanExecute 时的调用堆栈:

WpfApplication1.exe!WpfApplication1.MainWindow.Foo.get_Act.AnonymousMethod__1(object param) Line 30 WpfApplication1.exe!WpfApplication1.RelayCommand.CanExecute(object parameter) Line 41 + 0x1a bytes 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发件人,System.EventArgs e) + 0x5 字节 PresentationCore.dll!System.Windows.Input.CommandManager.CallWeakReferenceHandlers(System.Collections.Generic.List 处理程序) + 0xac 字节 PresentationCore.dll!System.Windows.Input.CommandManager.RaiseRequerySuggested(对象 obj) + 0xf 字节

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

是的。

4

2 回答 2

3

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

为了解决这个问题,我IDisposable在.RelayCommandRelayCommand

这是修改后RelayCommand的(原文在这里):

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
}

无论我在哪里使用上述内容,我都会跟踪所有实例化的 RelayCommands,以便我可以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();
}
于 2012-04-24T07:56:45.800 回答
0

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

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

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

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

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

用于 lambda 的弱事件处理程序模型

在 C# 中使用 Lambda 取消挂钩事件

使用 lambdas 作为事件处理程序会导致内存泄漏吗?

对于您的情况,最简单的方法是将您的 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<>Func<>委托一次,将它们存储在变量中,并在创建时使用这些变量,RelayCommand它将强制使用相同的实例。IMO,对于您的情况,这可能比它需要的更复杂。

于 2012-04-23T16:23:14.750 回答