【问题标题】:Binding variables as command parameter through binding expression通过绑定表达式将变量绑定为命令参数
【发布时间】:2011-09-13 04:31:04
【问题描述】:

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

【问题讨论】:

  • 你需要弄清楚你在问什么。提供您尝试过的代码也会有所帮助。

标签: c# .net wpf windows winforms


【解决方案1】:

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

【讨论】:

  • 您可以将命令绑定到类的某个属性,然后您可以将该属性值设置为您想要的局部变量,然后执行该命令。
【解决方案2】:

您需要更具体。可以发一些代码吗?

你可以这样做:

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>

希望这会有所帮助。

【讨论】:

  • 我想通过命令参数在按钮单击时发送属性值以查看模型。在属性中我设置了局部变量,所以我要求传递局部变量而不是询问属性值。
  • @Ravi 如果更新对您不起作用,您可以发布一些 XAML 和 View Model 类。
猜你喜欢
  • 2013-12-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-02-02
  • 2022-12-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多