Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

wpf command parameter from other object

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.

like image 792
DRapp Avatar asked Mar 07 '13 14:03

DRapp


People also ask

How do you pass a command parameter in WPF MVVM?

Passing a parameter to the CanExecute and Execute methods A parameter can be passed through the "CommandParameter" property. Once the button is clicked the selected address value is passed to the ICommand. Execute method. The CommandParameter is sent to both CanExecute and Execute events.

What is ICommand C#?

The ICommand interface is the code contract for commands that are written in . NET for Windows Runtime apps. These commands provide the commanding behavior for UI elements such as a Windows Runtime XAML Button and in particular an AppBarButton .

What is WPF CommandParameter?

CommandParameter - represents a user-defined data value that can be passed to the command when it is executed. CommandTarget - the object on which the command is being executed.

What does command parameter do?

The CommandParameter property is used to pass specific information to the command when it is executed. The type of the data is defined by the command. Many commands do not expect command parameters; for these commands, any command parameters passed will be ignored.


2 Answers

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}"/>
like image 112
Jehof Avatar answered Oct 10 '22 08:10

Jehof


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}"/>
like image 40
Tomtom Avatar answered Oct 10 '22 06:10

Tomtom