通过绑定表达式将变量绑定为命令参数

时间:2011-09-13 04:31:05

标签: c# .net wpf windows winforms

有没有办法将局部变量和对象绑定到命令作为命令参数。 如果以上任何一种都可以,请告诉我。

2 个答案:

答案 0 :(得分:0)

如果你的意思是绑定到“局部变量”,那么它显然是不可能的。您正在为某个对象设置DataContext,然后您只能绑定到其属性或dependencyproperties,而不是某些方法的局部变量,这听起来不合逻辑。

答案 1 :(得分:0)

你需要更加具体。你能发一些代码吗?

您可以执行以下操作:

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>

希望这有帮助。

相关问题