如何在XAML中使用CommandParameter

时间:2013-06-25 03:39:24

标签: windows-phone-7 windows-phone-8 windows-phone

我对如何在XAML中使用CommandParame有点迷失。我正在尝试绑定TextBox和Button。

这是我的XAML代码:

<TextBox x:Name="txtCity" Height="70"
         VerticalAlignment="Top"/>
<Button x:Name="btnCity"
        Content="Get"
        Background="CornflowerBlue"
        Height="70"
        Command="{Binding GetweatherCommand}"
        CommandParameter="{Binding ElementName=txtCity, Path=Text}"/>

在我的ViewModel类中,我有以下内容来处理clic操作:

ActionCommand getWeatherCommand;          //ActionCommand derivides from ICommand
public ActionCommand GetWeatherCommand
{
        get
        {
            if (getClimaCommand != null)
            {
                getClimaCommand = new ActionCommand(() =>
                    {
                        serviceModel.getClima("????");
                    });
            }

            return getWeatherCommand;
        }
 }

我的ActionCommand类:

public class ActionCommand : ICommand
{
    Action action;
    public ActionCommand(Action action)
    {
        this.action = action;
    }

    public bool CanExecute(object parameter)
    {
        return true;
    }

    public event EventHandler CanExecuteChanged;

    public void Execute(object parameter)
    {
        action();
    }
}

调试时,ExecuteCanExecute方法中的参数具有正确的值。但是,我想问题出在ViewClass (GetWeatherCommand)的方法中。我无法弄清楚如何传递参数。

所以,基于以上所述,有谁知道如何将参数传递给将要执行的方法?

1 个答案:

答案 0 :(得分:2)

ActionCommand.Execute忽略命令参数。试试这个:

public class ActionCommand<TParam> : ICommand
{
    Action<TParam> action;
    public ActionCommand(Action<TParam> action)
    {
        this.action = action;
    }

    public bool CanExecute(object parameter)
    {
        return true;
    }

    public event EventHandler CanExecuteChanged;

    public void Execute(object parameter)
    {
        action((TParam)parameter);
    }
}

然后:

getClimaCommand = new ActionCommand<string>(param =>
    {
        serviceModel.getClima(param);
    });