13

I'm wondering how to mark up the XAML for the following. I have a view model with an object based on ICommand.

I have a form with a textbox and a button. The button is hooked to the ICommand object via Command="{Binding MyButtonInViewModel}".

What I want to do is set the button's CommandParameter equal to whatever is in the text of the textbox such as to invoke a "Search", but obviously don't know how to hook across controls in the view.

DRapp
  • 47,638
  • 12
  • 72
  • 142

3 Answers3

23

The following XAML should work to pass the Text from the TextBox as Parameter to your command.

<TextBlock x:Name="searchBox" />

<Button Command="{Binding MyButtonInViewModel}" 
        CommandParameter="{Binding Text, ElementName=searchBox}"/>
Jehof
  • 34,674
  • 10
  • 123
  • 155
  • Thanks, Jehof. I think I have done the same thing. My impression is after doing this I should be able to get access to searchBox name in the MyButtonInViewModel function in my ViewModel. But I don't. Do you know why? (I am trying to pass a chart name instead of the text box) – Ehsan May 28 '19 at 18:41
7

You can do this by setting the ElementName in the binding. Here's an example:

<TextBox x:Name="textBox"/>
<Button Content="Button" 
        Command="{Binding ButtonCommand}" 
        CommandParameter="{Binding ElementName=textBox, Path=Text}"/>
ASh
  • 34,632
  • 9
  • 60
  • 82
Tomtom
  • 9,087
  • 7
  • 52
  • 95
4

If you bind the textbox itself to the button's command parameter, and not just the text property of the text box, you can manipulate the textbox in your view model to, for instance, clear the text property.

<TextBox x:Name="searchBox" />

<Button Command="{Binding MyButtonInViewModel}"
        CommandParameter="{Binding ElementName=searchBox}" />

View Model Code

private void SearchStuff(TextBox searchBox)
{
    //do stuff with searchBox.Text
    searchBox.Text = "";
}

Maybe not great for this example, where you probably want the search text to stay displayed along with the results of the search. Better for a logging or messaging app where you want the text to be 'consumed' when the button is clicked.

BrianHoyt
  • 41
  • 1
  • I appreciate your answer, but look at the answers... if any are provided with the checkmark, that means it is solved. This was almost a year ago and I am way beyond this item. – DRapp Feb 27 '14 at 17:07
  • 7
    @DRapp: answers on SO are not only for the person who asked the question, but also may be useful for the rest of the community. Whether it is a good idea to work with UI from VM is another question. – nightcoder Mar 18 '15 at 14:36