WPF:RadioButton 在加载时不引发事件

WPF: RadioButton do not raise event when its load

MainWindow.xaml

<Grid>
    <StackPanel>
        <RadioButton Content="A" GroupName="ASD"
                     Command="{Binding ButtonCommand}"
                     IsChecked="True"/>
        <RadioButton Content="B" GroupName="ASD"
                     Command="{Binding ButtonCommand}"/>
        <RadioButton Content="C" GroupName="ASD"
                     Command="{Binding ButtonCommand}"/>
    </StackPanel>
</Grid>

MainViewModel.cs

public class MainViewModel : BaseViewModel
    {
        private ICommand _buttonCommand;
        public ICommand ButtonCommand { get { return (_buttonCommand ?? new BaseCommand(MyAction)); } }

        public void MyAction()
        {
            Debug.WriteLine("clicked");
        }
    }

BaseCommand.cs

public class BaseCommand : ICommand
    {
        private Action _action;

        public BaseCommand(Action action)
        {
            _action = action;
        }

        public event EventHandler? CanExecuteChanged
        {
            add { CommandManager.RequerySuggested += value; }
            remove { CommandManager.RequerySuggested -= value; }
        }

        public bool CanExecute(object? parameter)
        {
            return true;
        }

        public void Execute(object? parameter)
        {
            _action();
        }
    }

当我点击按钮时,调用 MyAction() 并打印“clicked”,它工作正常。 当加载 window 时,我希望它引发事件点击,调用 MyAction() 并打印“已点击”,所以我设置第一个单选按钮 IsChecked 属性 = true,但它不引发事件。为什么?以及如何解决,谢谢。

事件和命令不一样。 RadioButoon 有很多事件来反映输入事件或状态变化,但只能调用一个命令。

要了解可用事件,请访问 API class class 参考,例如将光标移动到 class 名称上,然后按“F1”:RadioButton.

在您的情况下,您必须处理 RadioButton.Checked 事件。请注意,此事件将在 RadioButton 的初始化例程期间引发,以获取本地 IsChecked 值。如果你真的需要等到按钮在框架中加载(这意味着布局计算和渲染已经完成),你可以使用 DispatcherDispatcherPriority.Loaded 或直接延迟 Checked 事件处理 RadioButton.Loaded 事件(而不是使用 DispatcherChecked 事件):

<RadioButton Content="A"
             GroupName="ASD"
             Checked="RadioButton_Checked"
             Loaded="RadioButton_Loaded"
             IsChecked="True" />
private void RadioButton_Checked(object sender, RoutedEventArgs e)
{
  RadioButton radioButton = sender as RadioButton;
  // Handle IsChecked changed
  radionButton.Command.Execute(default);

  // Alternatively, wait until the control has loaded (in case you need to reference layout related properties)
  this.Dispatcher.InvokeAsync(() =>
  {
    radionButton.Command.Execute(default);
  }, DispatcherPriority.Loaded);

  // If this is a one-time operation, unregister the event handler
  radioButton.Checked -= RadioButton_Checked;
}

如前所述,如果您需要RadioButton完全加载,请考虑处理RadioButton.Loaded事件而不是使用Dispatcher