【发布时间】:2011-09-13 04:31:04
【问题描述】:
有没有办法将本地变量和对象绑定到命令作为命令参数。 如果以上任何一种可能,请告诉我。
【问题讨论】:
-
你需要弄清楚你在问什么。提供您尝试过的代码也会有所帮助。
标签: c# .net wpf windows winforms
有没有办法将本地变量和对象绑定到命令作为命令参数。 如果以上任何一种可能,请告诉我。
【问题讨论】:
标签: c# .net wpf windows winforms
如果您的意思是绑定到“局部变量”,那么它显然是不可能的。您正在为某个对象设置DataContext,然后您只能绑定到它的属性或依赖属性,而不是某些方法的局部变量,这听起来不合逻辑。
【讨论】:
您需要更具体。可以发一些代码吗?
你可以这样做:
ICommand command = new ActionCommand(parameter => { this.CallFunction(parameter); });
参数是一种对象类型,因此您可以传递任何单个对象,然后将其拆箱。 ActionCommand 还需要 Blend 或至少 Microsoft.Expression.Interactions 程序集。
更新
好的,在这种情况下,您最好在视图模型上定义 ICommand 并在 XAML 中绑定到它。
在视图模型上添加这样的实现:
public class AViewModel
{
private ICommand _ACommand;
public ICommand ACommand
{
get
{
if (this._ACommand == null)
{
this._ACommand = new ActionCommand(parameter =>
{
// do stuff.
});
}
return(this._ACommand);
}
}
}
在 XAML 中,您需要绑定到您可能已经完成的数据源。
<UserControl.Resources>
<local:AViewModel x:Key="AViewModelDataSource" />
</UserControl.Resources>
<Grid x:Name="LayoutRoot" DataContext="{Binding Source={StaticResource AViewModelDataSource}}">
<TextBox x:Name="ABCTextBox" />
<Button x:Name="AButton" Command="{Binding ACommand, Mode=OneWay}" CommandParameter="{Binding ElementName=ABCTextBox, Path=Text}" />
</Grid>
希望这会有所帮助。
【讨论】: