如何使用 DelegateCommand 将信息从 View 传递到 ViewModel? [英] How do I pass the information from View to ViewModel with DelegateCommand?

查看:54
本文介绍了如何使用 DelegateCommand 将信息从 View 传递到 ViewModel?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的视图中,我有一个按钮.

In my View, I have a button.

当用户单击此按钮时,我想让 ViewModel 将 TextBlock 的上下文保存在数据库中.

When the user clicks this button, I want to have the ViewModel save the context of the TextBlock in the database.

<StackPanel HorizontalAlignment="Left" VerticalAlignment="Top">
    <TextBlock Text="{Binding FirstName}"/>
    <TextBox Text="Save this text to the database."/>
    <Button Content="Save" Command="{Binding SaveCommand}"/>
</StackPanel>

但是,在我的 ViewModel 中的 DelegateCommand 中,Save()"方法不传递任何参数,那么此时我如何从视图中获取数据?

However, in my DelegateCommand in my ViewModel, the "Save()" method doesn't pass any arguments, so how do I get data from the view at that point?

#region DelegateCommand: Save
private DelegateCommand saveCommand;

public ICommand SaveCommand
{
    get
    {
        if (saveCommand == null)
        {
            saveCommand = new DelegateCommand(Save, CanSave);
        }
        return saveCommand;
    }
}

private void Save()
{
    TextBox textBox = ......how do I get the value of the view's textbox from here?....
}

private bool CanSave()
{
    return true;
}
#endregion

推荐答案

查看 Josh Smith 撰写的这篇 MSDN 文章.在其中,他展示了他称为 RelayCommand 的 DelegateCommand 的变体,并且 RelayCommand 上的 Execute 和 CanExecute 委托接受类型为 object 的单个参数.

Check out this MSDN article by Josh Smith. In it, he shows a variation of DelegateCommand that he calls RelayCommand, and the Execute and CanExecute delegates on RelayCommand accept a single parameter of type object.

使用 RelayCommand,您可以通过 CommandParameter 将信息传递给代表:

Using RelayCommand you can pass information to the delegates via a CommandParameter:

<Button Command="{Binding SaveCommand}" 
        CommandParameter="{Binding SelectedItem,Element=listBox1}" />

更新

这篇文章,似乎有一个泛型以类似方式接受参数的 DelegateCommand 版本.您可能想尝试将 SaveCommand 更改为 DelegateCommand 并更改 Save 和 CanSave 方法,以便它们采用 MyObject 参数.

Looking at this article, it appears that there is a generic version of DelegateCommand which accepts a parameter in a similar way. You might want to try changing your SaveCommand to a DelegateCommand<MyObject> and change your Save and CanSave methods so that they take a MyObject parameter.

这篇关于如何使用 DelegateCommand 将信息从 View 传递到 ViewModel?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆