UIから削除されたコマンドソースでCanExecuteが呼び出される理由を理解しようとしています。ここで実証するための単純化されたプログラムです:コマンドソースが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です。マイケルEdenfieldの質問に
回答:
Q1:CanExecuteは削除ボタンで呼び出されたときのコールスタック:!
WpfApplication1.exe WpfApplication1.MainWindow.Foo.get_Act.AnonymousMethod__1(オブジェクトパラメーター)行30 WpfApplication1.exe!WpfApplication1.RelayCommand.CanExecute(オブジェクトパラメーター)行41 + 0x1aバイト PresentationFramework.dll!MS.Internal.Commands.CommandHelpers.CanExecuteCommandSource(Syste + 0x8 bytes PresentationFramework.dll!System.Windows.Controls.Primitives.ButtonBase.OnCanExecuteChanged(Object() System.Windows.Input.CommandManager.CallWeakReferenceHandlers(System.Collections.Generic.Listハンドラー)+ 0xac bytes PresentationCore.dll!System.Windows.Input.CommandManager。 RaiseRequerySuggested(オブジェクトobj)+ 0xFのバイト
Q2:リストからすべてのボタンを削除する場合も、これは(?ちょうど最初ではない)が起こっておくん
はい。
私はRelayCommandが恋しい。これは何ですか? – Gqqnbig
RelayCommandの実装へのリンクを追加しました。 –
あなたはイベント中にコールスタックをチェックし、それをトリガしたものを見てみましたか?また、リストから*すべての*ボタンを削除しても、これは起こり続けますか? –