PVi*_*itt 5 wpf xaml commandbinding
我在视图上有一个按钮,它通过RoutedUICommand绑定到ViewModel中定义的命令.
XAML代码摘自视图:
<Button Content="Login" Command="{Binding Login}" />
Run Code Online (Sandbox Code Playgroud)
在View的CodeBehind中,我将ViewModel中的命令绑定添加到视图的绑定集合中:
this.CommandBindings.Add( viewModel.LoginCommandBinding );
Run Code Online (Sandbox Code Playgroud)
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;
}
}
Run Code Online (Sandbox Code Playgroud)
因此命令被定义为文本和名称"登录".按钮本身的内容为"登录".有没有办法使用命令的文本作为按钮的内容?
Car*_*lin 14
您可以为每个按钮动态获取命令文本.
将它放在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>
Run Code Online (Sandbox Code Playgroud)
从...
http://leecampbell.blogspot.com/2008/12/wpf-commandtext.html
实现此目的的一个好方法是使用RelativeSource标记扩展将其绑定回来,例如, Command="Cmds:MyCommands.TestCmd" Content="{Binding RelativeSource={RelativeSource Self}, Path=Command.Text}"
只需绑定到命令中的 Name 或 Text 属性,如下所示:
<Button x:Name="btnName"
Command="{Binding ThisIsMyCommand}"
Content="{Binding ThisIsMyCommand.Name}" />
<Button x:Name="btnText"
Command="{Binding ThisIsMyCommand}"
Content="{Binding ThisIsMyCommand.Text}" />
Run Code Online (Sandbox Code Playgroud)