Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use the text of a routed command as button content

I have a button on a view that is bound via a RoutedUICommand to a command defined in the ViewModel.

The XAML code excerpt from the view:

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

In the View's CodeBehind I add the command binding from the ViewModel to the view's binding collection:

this.CommandBindings.Add( viewModel.LoginCommandBinding );

The ViewModel 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 name both "Login". The button itself has the content "Login". Is there a way to use the command's text as the button's content?

like image 975
PVitt Avatar asked Sep 22 '10 13:09

PVitt


1 Answers

You can get the command text dynamically for every button.

Put this in your Application.xaml file.

<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>

From...

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

like image 197
Carter Medlin Avatar answered Nov 15 '22 10:11

Carter Medlin