【问题标题】:How to pass two parameters to ViewModel class in Silverlight?如何将两个参数传递给 Silverlight 中的 ViewModel 类?
【发布时间】:2010-08-19 08:48:29
【问题描述】:

我正在研究将 MVVM 模式用于我的 Silverlight 应用程序。

以下代码来自 xaml UI 代码:

<Button Width="30" 
        Margin="10" 
        Content="Find"
        Command="{Binding Path=GetCustomersCommand, Source={StaticResource customerVM}}"
        CommandParameter="{Binding Path=Text, ElementName=tbName}"/>

<TextBox x:Name="tbName" 
         Width="50" />

<TextBox x:Name="tbID" 
         Width="50" />

以下代码来自 ViewModel 类:

public ICommand GetCustomersCommand
{
    get { return new RelayCommand(GetCustomers) { IsEnabled = true }; }
}

public void GetCustomers(string name, string id)
{
    // call server service (WCF service)
}

我需要传递两个参数,但是不知道如何将两个参数(id 和 name)传递给 ViewModel 类。

我想知道是否可以在 xaml 代码中而不是在代码隐藏中。

提前致谢

【问题讨论】:

    标签: mvvm silverlight-4.0


    【解决方案1】:

    没有简单的方法可以做到这一点。相反,我建议您创建一个不带参数的命令,并将框 TextBoxes 绑定到 ViewModel 的属性:

    C#

    public void GetCustomers()
    {
        GetCustomers(_id, _name);
    }
    
    private int _id;
    public int ID
    {
        get { return _id; }
        set
        {
            _id = value;
            OnPropertyChanged("ID");
        }
    }
    
    private string _name;
    public string Name
    {
        get { return _name; }
        set
        {
            _name = value;
            OnPropertyChanged("Name");
        }
    }
    

    XAML

    <Button Width="30" 
            Margin="10" 
            Content="Find"
            Command="{Binding Path=GetCustomersCommand, Source={StaticResource customerVM}}"/>
    
    <TextBox x:Name="tbName"
             Text="{Binding Path=Name, Source={StaticResource customerVM}, Mode=TwoWay}"
             Width="50" />
    
    <TextBox x:Name="tbID" 
             Text="{Binding Path=ID, Source={StaticResource customerVM}, Mode=TwoWay}"
             Width="50" />
    

    【讨论】:

    • 感谢您的回复,它解决了我的问题,但是 Silverlight 中似乎需要多绑定功能。
    • 多重绑定?为什么 ?您一次只能绑定一个属性,因此简单的绑定可以正常工作
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-08
    • 2021-07-07
    • 1970-01-01
    • 2022-11-10
    相关资源
    最近更新 更多