You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

MVVM中RelayCommand传递参数始终为null的问题求助

RelayCommand传参始终为null的解决办法

问题根源

你把CommandParameter设置在Button标签上,但通过InvokeCommandAction执行命令时,它不会自动读取Button的CommandParameter值,必须把参数直接配置在InvokeCommandAction内部。

修正方案1:调整InvokeCommandAction配置

将CommandParameter从Button标签移到InvokeCommandAction节点中:

<Button
   Margin="0,8,8,0"
   Content="Ok"
   IsDefault="True"
   Style="{StaticResource MaterialDesignFlatButton}">
         <i:Interaction.Triggers>
             <i:EventTrigger
                 EventName="Click">                                        
                 <i:InvokeCommandAction
                     Command="{Binding CreateNewCommand}"
                     CommandParameter="Sample"/> <!-- 参数移至此处 -->
             </i:EventTrigger>
         </i:Interaction.Triggers>
 </Button>

如果需要传递动态参数(比如绑定控件属性),也可以在这里使用绑定语法:

CommandParameter="{Binding ElementName=UserNameTextBox, Path=Text}"

修正方案2:直接使用Button的Command属性(更简洁)

如果只是响应Button的Click事件,完全不需要用Interaction.Triggers,直接给Button设置Command和CommandParameter即可,此时参数会自动传递:

<Button
   Margin="0,8,8,0"
   Content="Ok"
   IsDefault="True"
   Command="{Binding CreateNewCommand}"
   CommandParameter="Sample"
   Style="{StaticResource MaterialDesignFlatButton}"/>

以上两种方式都能解决你遇到的参数为null的问题。

内容的提问来源于stack exchange,提问作者Paslet87

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.13 10:42:15