【发布时间】:2010-10-23 01:14:29
【问题描述】:
我想通过使用 RelayCommand 将我的应用程序的 XAML(视图)中定义的参数传递给 ViewModel 类。我关注了Josh Smith's excellent article on MVVM,并实现了以下内容。
XAML 代码
<Button
Command="{Binding Path=ACommandWithAParameter}"
CommandParameter="Orange"
HorizontalAlignment="Left"
Style="{DynamicResource SimpleButton}"
VerticalAlignment="Top"
Content="Button"/>
ViewModel 代码
public RelayCommand _aCommandWithAParameter;
/// <summary>
/// Returns a command with a parameter
/// </summary>
public RelayCommand ACommandWithAParameter
{
get
{
if (_aCommandWithAParameter == null)
{
_aCommandWithAParameter = new RelayCommand(
param => this.CommandWithAParameter("Apple")
);
}
return _aCommandWithAParameter;
}
}
public void CommandWithAParameter(String aParameter)
{
String theParameter = aParameter;
}
#endregion
我在 CommandWithAParameter 方法中设置了一个断点,并观察到 aParameter 设置为“Apple”,而不是“Orange”。这似乎很明显,因为使用文字字符串“Apple”调用了 CommandWithAParameter 方法。
但是,查看执行堆栈,我可以看到“橙色”,我在XAML中设置的CommandParameter是ICommand Execute接口方法的RelayCommand实现的参数值。
即执行栈下面方法中的参数值为“橙色”,
public void Execute(object parameter)
{
_execute(parameter);
}
我想弄清楚的是如何创建 RelayCommand ACommandWithAParameter 属性,以便它可以使用 XAML 中定义的 CommandParameter“Orange”调用 CommandWithAParameter 方法。
有没有办法做到这一点?
我为什么要这样做? “即时本地化”的一部分 在我的特定实现中,我想创建一个可以绑定到多个按钮的 SetLanguage RelayCommand。我想将两个字符语言标识符(“en”、“es”、“ja”等)作为 CommandParameter 传递,并为 XAML 中定义的每个“设置语言”按钮进行定义。我想避免必须为每种支持的语言创建 SetLanguageToXXX 命令,并将两个字符语言标识符硬编码到 ViewModel 中的每个 RelayCommand 中。
【问题讨论】:
-
对这个问题提供的答案都没有帮助我创建一个 RelayCommand 对象来与需要参数输入的方法进行通信。如果有人有类似的问题,这个帖子帮助了我:stackoverflow.com/questions/5298910/…
标签: .net wpf data-binding mvvm lambda