問題是這樣的。假設我有3個切換按鈕,並且我希望只有一個正在使用Command進行檢查。當一個按鈕被選中時,其他人應該被禁用。 (我不想使用單選按鈕)。 所以我創建了這個簡單的代碼,但奇怪的是,當點擊選中按鈕命令執行沒有執行(沒有顯示MessageBox)。切換按鈕命令未執行
<Window x:Class="ToggleButtonsProblem.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<StackPanel>
<ToggleButton Command="{Binding ToggleCommand}" CommandParameter="{Binding RelativeSource={RelativeSource Self}}">A</ToggleButton>
<ToggleButton Command="{Binding ToggleCommand}" CommandParameter="{Binding RelativeSource={RelativeSource Self}}">B</ToggleButton>
<ToggleButton Command="{Binding ToggleCommand}" CommandParameter="{Binding RelativeSource={RelativeSource Self}}">C</ToggleButton>
</StackPanel>
using System;
using System.Windows;
using System.Windows.Input;
using System.Windows.Controls.Primitives;
namespace ToggleButtonsProblem {
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window {
public MainWindow() {
InitializeComponent();
this.DataContext = new ViewModel();
}
}
public class ViewModel {
public static ICommand ToggleCommand { get { return new ToggleCommand(); } }
}
public class ToggleCommand : ICommand {
public static bool isSomeChecked = false;
public static ToggleButton currentCheckedButton;
public bool CanExecute(object parameter) {
if (currentCheckedButton == null) return true;
return (parameter as ToggleButton).IsChecked == true;
}
public event EventHandler CanExecuteChanged {
add { CommandManager.RequerySuggested += value; }
remove { CommandManager.RequerySuggested -= value; }
}
public void Execute(object parameter) {
currentCheckedButton = null;
ToggleButton button = parameter as ToggleButton;
MessageBox.Show(button.IsChecked.ToString());
if (button.IsChecked == true) {
currentCheckedButton = button;
}
else {
currentCheckedButton = null;
}
}
}
}
正如你所說的:「只有按下按鈕時才執行命令。」這也意味着未經檢查。嘗試將ToggleCommand的CanExecute更改爲「返回true」,並且您看到Execute方法在選中時被觸發並且未選中。順便說一下,我認爲定義事件和命令在同一時間是不好的做法(更不用說我需要命令來實現MVVM):) –
編輯:是的,這是工作,我認爲你是正確的與你的解釋:) –