5

我在视图上有一个按钮,该按钮通过 RoutedUICommand 绑定到 ViewModel 中定义的命令。

视图中的 XAML 代码摘录:

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

在 View 的 CodeBehind 中,我将 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

4 回答 4

15

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

把它放在你的 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

于 2012-06-19T16:24:10.580 回答
6

实现此目的的一个好方法是使用 RelativeSource 标记扩展将其绑定回来,例如,Command="Cmds:MyCommands.TestCmd" Content="{Binding RelativeSource={RelativeSource Self}, Path=Command.Text}"

于 2012-01-12T20:49:58.260 回答
3

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

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

        <Button x:Name="btnText"
                Command="{Binding ThisIsMyCommand}"
                Content="{Binding ThisIsMyCommand.Text}" />
于 2010-09-22T13:23:43.413 回答
0

我现在没有基础设施来测试这个,但我对这个问题的纪念是按钮应该自动使用 RoutedUICommand 文本作为它的内容。

您是否尝试过删除 Content 属性?

于 2010-09-22T13:25:28.307 回答