How to use routed command text as button content

I have a button on a view connected via RoutedUICommand to a command defined in ViewModel.

Outputting XAML code from a view:

<Button Content="Login" Command="{Binding Login}" />

In the CodeBehind view, I add the command binding from the ViewModel to the view binding collection:

this.CommandBindings.Add( viewModel.LoginCommandBinding );

The ViewModel model itself implements the command:

public class LoginViewModel:ViewModelBase
{

    public ICommand Login { get; private set; }
    public CommandBinding LoginCommandBinding { get; private set; }

    public LoginViewModel( ) {
        this.Login = 
            new RoutedUICommand( "Login", "Login", typeof( Window ) );
        this.LoginCommandBinding = 
            new CommandBinding( Login, LoginCommandHandler, CanExecuteHandler );
    }

    void LoginCommandHandler( object sender, ExecutedRoutedEventArgs e ) {
        //Put code here
    }

    void CanExecuteHandler( object sender, CanExecuteRoutedEventArgs e ) {
        return true;
    }
}

So, the command was defined with the text and the name "Input". The button itself has the contents of the "Login". Is there a way to use command text as button content?

+5
source share
4 answers

Just bind the Name or Text property in the command, for example:

        <Button x:Name="btnName"
                Command="{Binding ThisIsMyCommand}"
                Content="{Binding ThisIsMyCommand.Name}" />

        <Button x:Name="btnText"
                Command="{Binding ThisIsMyCommand}"
                Content="{Binding ThisIsMyCommand.Text}" />
+3
source

.

Application.xaml.

<Style TargetType="Button">
  <!--Default Button content to be the Text provided from the Command.-->
  <Setter Property="Content" 
          Value="{Binding RelativeSource={RelativeSource Self}, 
           Path=Command.Text}"/>
</Style>

...

http://leecampbell.blogspot.com/2008/12/wpf-commandtext.html

+13

- RelativeSource, , Command="Cmds:MyCommands.TestCmd" Content="{Binding RelativeSource={RelativeSource Self}, Path=Command.Text}"

+5

, , , RoutedUICommand .

Content?

0

All Articles