代码之家  ›  专栏  ›  技术社区  ›  PVitt

如何将路由命令的文本用作按钮内容

  •  5
  • PVitt  · 技术社区  · 14 年前

    视图中的XAML代码摘录:

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

    在视图的代码隐藏中,我将命令绑定从ViewModel添加到视图的绑定集合:

    this.CommandBindings.Add( viewModel.LoginCommandBinding );
    

    ViewModel本身执行以下命令:

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

    4 回复  |  直到 14 年前
        1
  •  3
  •   Wonko the Sane    14 年前

    只需绑定到命令中的Name或Text属性,如下所示:

            <Button x:Name="btnName"
                    Command="{Binding ThisIsMyCommand}"
                    Content="{Binding ThisIsMyCommand.Name}" />
    
            <Button x:Name="btnText"
                    Command="{Binding ThisIsMyCommand}"
                    Content="{Binding ThisIsMyCommand.Text}" />
    
        2
  •  15
  •   Carter Medlin    13 年前

    您可以动态地获取每个按钮的命令文本。

    把这个放进你的口袋里应用程序.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

        3
  •  5
  •   Dan    13 年前

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

        4
  •  0
  •   Timores    14 年前

    是否尝试删除内容属性?