Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/257.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/fsharp/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 通过绑定表达式将变量绑定为命令参数_C#_.net_Wpf_Windows_Winforms - Fatal编程技术网

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

C# 通过绑定表达式将变量绑定为命令参数,c#,.net,wpf,windows,winforms,C#,.net,Wpf,Windows,Winforms,有没有办法将本地变量和对象绑定到命令作为命令参数。 如果上述任何一项都是可能的,那么请告诉我。如果你指的是绑定到“局部变量”,那么这显然是不可能的。您正在为某个对象设置DataContext,然后您只能绑定到其属性或dependencyproperties,而不能绑定到某些方法的局部变量,这听起来不符合逻辑。您需要更具体一些。你能发一些代码吗 您可以执行以下操作: ICommand command = new ActionCommand(parameter => { this.CallFu

有没有办法将本地变量和对象绑定到命令作为命令参数。
如果上述任何一项都是可能的,那么请告诉我。

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

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

您可以执行以下操作:

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>


希望这能有所帮助。

您需要澄清您的问题。提供您尝试过的代码也会有所帮助。我想将视图中的属性值发送到“在按钮上查看模型”并单击命令参数。在属性中,我设置了局部变量,因此我要求传递局部变量,而不是询问属性值。@如果更新对您不起作用,您可以发布一些XAML和视图模型类。您可以将命令绑定到类的属性,然后将该属性值设置为所需的局部变量,然后执行该命令。