5

RoutedUICommandを介してViewModelで定義されたコマンドにバインドされているビューにボタンがあります。

ビューからのXAMLコードの抜粋:

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

ビューの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 に答える