我正在开发一个WPF应用程序,并且有一个TextBlock,我想使用命令绑定在单击时触发命令。实现这一目标的最佳方法是什么?
TextBlock控件没有Command属性,但它有一个CommandManager。这是什么?它可以用于命令绑定吗?我已经看到许多其他控件以及此属性..
我是否有一些可以使用的监督控制?是吗?建议使用按钮并将其设置为不像按钮?
是否有一些控件支持Command绑定,我可以将其包裹在TextBlock中?
我应该创建一个基本上是TextBlock的自定义控件,但是具有额外的属性Command和CommandArgument,它可以启用命令绑定,例如MouseLeftButtonDown属性。
答案 0 :(得分:17)
我是否有一些可以使用的监督控制?是吗?建议使用按钮并将其设置为不像按钮?
是。最简单的方法是重新模板化一个按钮,使其像TextBlock一样,并利用按钮类的命令属性。
这样的事情:
<ControlTemplate TargetType="Button">
<TextBlock Text="{TemplateBinding Content}" />
</ControlTemplate>
...
<Button Content="Foo" Command="{Binding Bar}" />
答案 1 :(得分:2)
以下XAML可用于向WPF TextBlock添加命令绑定,然后WPF TextBlock将处理鼠标操作。
<TextBlock FontWeight="Bold" Text="Header" Cursor="Hand">
<TextBlock.InputBindings>
<MouseBinding Command="ApplicationCommands.Cut" MouseAction="LeftClick"/>
</TextBlock.InputBindings>
</TextBlock>
Command
可以是内置应用程序命令之一,它将使用上面显示的语法,或者它可以是继承自Command
接口的自定义ICommand
。在这种情况下,语法将是:
<MouseBinding Command="{Binding myCustomCommand}" MouseAction="LeftClick"/>
MouseAction
没有提供任何关于放置什么的智能感知提示(在VS2015中),因此您必须进行一些挖掘才能获得有效的枚举。
自.NET 4.5起,MouseAction
的有效条目为:
上面显示的常量取自MSDN。
答案 2 :(得分:0)
<Window.Resources>
<CommandBinding x:Key="binding" Command="ApplicationCommands.Save" Executed="SaveCommand" CanExecute="SaveCommand_CanExecute" />
</Window.Resources>
<TextBox Margin="5" Grid.Row="2" TextWrapping="Wrap" AcceptsReturn="True" TextChanged="txt_TextChanged">
<TextBox.CommandBindings>
<StaticResource ResourceKey="binding"></StaticResource>
</TextBox.CommandBindings>
</TextBox>
吗?