
主視窗.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>
主視圖模型.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() 并列印“單擊”,它作業正常。加載視窗時,我希望它的引發事件單擊,呼叫 MyAction() 并列印“單擊”,所以我設定第一個單選按鈕 IsChecked 屬性 = true,但它不引發事件。為什么?以及如何解決,謝謝。
uj5u.com熱心網友回復:
事件和命令不一樣。RadioButoon有許多事件來反映輸入事件或狀態變化,但只能呼叫一個命令。
要了解可用的事件,請訪問該類的 API 類參考,例如,將游標移到類名上,然后按“F1”:RadioButton。
在您的情況下,您必須處理該RadioButton.Checked事件。請注意,此事件將在 的初始化例程期間引發RadioButton,以便獲取本地IsChecked值。如果您確實需要等到按鈕以框架術語加載(這意味著布局計算和渲染已完成),您可以使用a推遲Checked事件或直接處理事件(而不是使用事件旁邊的事件):DispatcherDispatcherPriority.LoadedRadioButton.LoadedCheckedDispatcher
<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.
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/472173.html
標籤:wpf
