使用命令将参数传递到viewmodel

Ras*_*ard 6 c# data-binding wpf xaml mvvm

我无法将视图中的参数发送到我的viewmodel.

View.xaml:

在我看来,我有以下几点:

<TextBox
    MinWidth="70"
    Name="InputId"/>

<Button 
    Command="{Binding ButtonCommand}"
    CommandParameter="{Binding ElementName=InputId}"
    Content="Add"/>
Run Code Online (Sandbox Code Playgroud)

View.xaml.cs:

public MyView()
{
    InitializeComponent();
}

public MyView(MyViewModel viewModel) : this()
{
    DataContext = viewModel;
}
Run Code Online (Sandbox Code Playgroud)

MyViewModel.cs:

public class MyViewModel : BindableBase
{
    public ICommand ButtonCommand { get; private set; }

    public MyViewModel()
    {
        ButtonCommand = new DelegateCommand(ButtonClick);
    }

    private void ButtonClick()
    {
        //Read 'InputId' somehow. 
        //But DelegateCommand does not allow the method to contain parameters.
    }
}
Run Code Online (Sandbox Code Playgroud)

有什么建议,InputId当我点击按钮到我的viewmodel时,我怎么能通过?

小智 11

您需要<object>像这样添加到您的委托命令:

public ICommand ButtonCommand { get; private set; }

     public MyViewModel()
        {
            ButtonCommand = new DelegateCommand<object>(ButtonClick);
        }

        private void ButtonClick(object yourParameter)
        {
            //Read 'InputId' somehow. 
            //But DelegateCommand does not allow the method to contain parameters.
        }
Run Code Online (Sandbox Code Playgroud)

您是否希望将文本框的文本更改为您的xaml:

CommandParameter="{Binding Text,ElementName=InputId}" 
Run Code Online (Sandbox Code Playgroud)

  • 谷歌搜索30分钟后,这是迄今为止最好的解释.谢谢! (4认同)