我的表單有 2 個單選按鈕。當您按下它們中的任何一個時,它會執行一個命令,該命令設定一個字串變數,并將單選按鈕的相對值設定為 true - 這還有一個 CommandParameter 將字串 Content 的值發送到 Exectue 函式。
當一個人按下單選按鈕時,這很好用。變數得到設定,一切都很好。
但是,我在 xaml 中編碼了一個單選按鈕,默認設定為選中 - 這不會導致在第一次啟動表單時執行命令。因此,我為選中的單選按鈕保留適當值的字串變數永遠不會被設定。
如何讓我的字串變數在啟動時從 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>
這是視圖模型:
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);
}
uj5u.com熱心網友回復:
僅當用戶單擊按鈕時才會呼叫該命令。
更改 RadioButton 的狀態會引發 Checked 和 Unchecked 事件。您可以將命令連接到 Checked 事件,但不能保證 IsChecked 屬性在偵聽器連接后會更改。因為兩者都是在 XAML 中指定的。
在我看來,最正確的做法是在 XAML 初始化之后呼叫 Code Behind 中的命令。
InitializeComponent();
if (TsMapPane.Command is ICommand command &&
command.CanExecute(TsMapPane.CommandParameter))
{
command.Execute(TsMapPane.CommandParameter);
}
PS您可以在解決方案中添加以下擴展方法:
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 = onl oaded;
}
private void OnLoaded(object sender, RoutedEventArgs e)
{
Loaded -= onl oaded;
TsMapPane.TryExecute();
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/537158.html
標籤:C#wpfxaml