问题是这个。假设我有3个切换按钮,我想只使用Command检查一个按钮。选中一个按钮时,应禁用其他按钮。 (我不想使用单选按钮)。 所以我创建了这个简单的代码,但奇怪的是,当单击选中按钮时,命令Execute不会执行(不显示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;
}
}
}
}
答案 0 :(得分:1)
仅在按下按钮时才执行命令。您需要挂钩ToggleButton的Unchecked事件,例如:
<ToggleButton Command="{Binding ToggleCommand}" Unchecked="ToggleButton_Unchecked" CommandParameter="{Binding RelativeSource={RelativeSource Self}}">A</ToggleButton>
将方法处理程序添加到代码隐藏类:
public void ToggleButton_Unchecked(object sender, RoutedEventArgs e) {
(sender as ToggleButton).Command.Execute(sender);
}
这应该有用,也许你可以找到一些更漂亮的方法来添加方法处理程序,也许作为ToggleCommand类的一部分。
编辑: 尝试实现这样的CanExecute()方法:
public bool CanExecute(object parameter) {
if (currentCheckedButton == null) return true;
return currentCheckedButton == parameter;
}
对我而言,它有效。以下是我认为导致问题的原因:您单击(取消选中)按钮,因此IsChecked更改为false。然后WPF尝试调用Execute()方法,但是一如既往地首先调用CanExecute()。但是,CanExecute()返回false,因为检查状态已经更改,因此不会调用Execute()方法。
答案 1 :(得分:0)
ToggleCommand不应该是静态的。尝试将命令定义为属性。