命令不执行窗体初始化的单选按钮



我的表单有两个单选按钮。当你按下它们中的任何一个时,它会执行一个命令,该命令将一个字符串变量与单选按钮的相对值设置为true -这还有一个CommandParameter,它将字符串Content的值发送到execute函数。

当一个人按下单选按钮时,这很好。变量设置好了,一切都好。

但是,我在xaml中编码了其中一个单选按钮,默认设置为checked,这不会导致该命令在第一次启动表单时执行。因此,我为选中的单选按钮保存适当值的字符串变量永远不会被设置。

我如何让我的字符串变量从Execute(param)方法启动时接收值?

这里是xaml:

<StackPanel Grid.Row="4" Grid.Column="1" Margin="3"  Orientation="Horizontal">
<RadioButton GroupName="LcType" Name="TsMapPane" HorizontalAlignment="Left" Checked="TsMapPane_Checked" IsChecked="True"
Command="{Binding Path=LcTypeCommand}" CommandParameter="{Binding ElementName=TsMapPaneTextBox, Path=Text}" >
<RadioButton.Content>
<TextBlock Name="TsMapPaneTextBox" Text="TS_MAP_PANE"/>
</RadioButton.Content>
</RadioButton>
<RadioButton GroupName="LcType" Margin="10 0 0 0"  Name="TsGroup" HorizontalAlignment="Left" Checked="TsGroup_Checked"
Command="{Binding Path=LcTypeCommand}" CommandParameter="{Binding ElementName=TsGroupTextBox, Path=Text}">
<RadioButton.Content>
<TextBlock Name="TsGroupTextBox" Text="TS_GROUP"/>
</RadioButton.Content>
</RadioButton>
</StackPanel>

这是ViewModel:

public ICommand LcTypeCommand { get; set; }
public MyViewModel()
{
LcTypeCommand = new RelayCommand((param) => LcTypeExecute(param), () => true);
}
private void LcTypeExecute(object param)
{
LcTypeName = param.ToString();
}
public string LcTypeName
{
get => _lcTypeName;
set => SetField(ref _lcTypeName, value);
}

该命令仅在用户单击按钮时调用。
更改RadioButton的状态会引发Checked和Unchecked事件。您可以将命令连接到Checked事件,但不能保证在连接侦听器后IsChecked属性将被更改。因为两者都是在XAML中指定的。
在我看来,最正确的是在XAML初始化之后调用Code Behind中的命令。

InitializeComponent();
if (TsMapPane.Command is ICommand command &&
command.CanExecute(TsMapPane.CommandParameter))
{
command.Execute(TsMapPane.CommandParameter);
}

注:您可以在解决方案中添加以下扩展方法:

public static partial class WinHelper
{
public static void TryExecute(this ICommandSource commandSource)
{
if (commandSource.Command is not ICommand command)
return;
if (command is RoutedCommand routedCommand)
{
IInputElement? target = commandSource.CommandTarget ?? commandSource as IInputElement;
if (routedCommand.CanExecute(commandSource.CommandParameter, target))
{
routedCommand.Execute(commandSource.CommandParameter, target);
}
}
else
{
if (command.CanExecute(commandSource.CommandParameter))
{
command.Execute(commandSource.CommandParameter);
}
}
}
}

那么代码将被简化为:

InitializeComponent();
TsMapPane.TryExecute();

显示了"TsMapPane.CommandParameter"空值

在XAML初始化时,如果DataContext是由外部容器分配的,那么对DataContext的绑定将无法工作。因此,您需要在Loaded事件中执行一次命令:

public SomeWindow()
{
InitializeComponent();
Loaded += OnLoaded;
}
private void OnLoaded(object sender, RoutedEventArgs e)
{
Loaded -= OnLoaded;
TsMapPane.TryExecute();
}