【发布时间】: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:我更新了答案。