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

喜欢而已 提交于 2019-12-23 10:57:06

问题


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?


回答1:


Just bind to the Name or Text property in the command, like so:

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

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



回答2:


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




回答3:


A good way to achieve this is to bind it back using the RelativeSource markup extension e.g., Command="Cmds:MyCommands.TestCmd" Content="{Binding RelativeSource={RelativeSource Self}, Path=Command.Text}"




回答4:


I don't have the infrastructure to test this right now, but my souvenir of this issue is that the button should automatically use the RoutedUICommand text as its content.

Have you tried removing the Content property ?



来源:https://stackoverflow.com/questions/3769533/how-to-use-the-text-of-a-routed-command-as-button-content

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!