15

我正在开发一个 WPF 应用程序,并且有一个 TextBlock,我想在单击时使用命令绑定来触发命令。实现这一目标的最佳方法是什么?

  • TextBlock 控件没有 Command 属性,但它有 CommandManager。这是什么?它可以用于命令绑定吗?我已经看到了许多其他控件以及此属性..

  • 是否有一些我监督过的可以使用的控制?例如是否建议使用按钮并将其样式设置为看起来不像按钮?

  • 是否有一些支持命令绑定的控件,我可以将它们包裹在 TextBlock 周围?

  • 我是否应该创建一个自定义控件,它基本上是一个 TextBlock,但具有额外的属性 Command 和 CommandArgument,可以在例如 MouseLeftButtonDown 属性上启用命令绑定。

4

3 回答 3

17

是否有一些我监督过的可以使用的控制?例如是否建议使用按钮并将其样式设置为看起来不像按钮?

是的。最简单的方法是将按钮重新模板化,使其像 TextBlock 一样,并利用按钮类的命令属性。

像这样的东西:

<ControlTemplate TargetType="Button">
        <TextBlock Text="{TemplateBinding Content}" />
    </ControlTemplate>
...
<Button Content="Foo" Command="{Binding Bar}" />
于 2009-11-24T16:57:32.243 回答
4

下面的 XAML 可用于将命令绑定添加到 WPF 文本块,然后该文本块将作用于鼠标操作。

<TextBlock FontWeight="Bold" Text="Header" Cursor="Hand">
    <TextBlock.InputBindings>
        <MouseBinding Command="ApplicationCommands.Cut" MouseAction="LeftClick"/>
    </TextBlock.InputBindings>
</TextBlock>

Command可以是内置应用程序命令之一,它将使用如上所示的语法,也可以是从接口继承的自定义命令CommandICommand在这种情况下,语法将是:

<MouseBinding Command="{Binding myCustomCommand}" MouseAction="LeftClick"/>

MouseAction没有提供任何有关放置内容的 Intellisense 提示(在 VS2015 中),因此您必须进行一些挖掘才能获得有效的枚举。

从 .NET 4.5 开始,有效条目为MouseAction

  • LeftClick - 鼠标左键单击。
  • LeftDoubleClick - 鼠标左键双击。
  • MiddleClick - 鼠标中键单击。
  • MiddleDoubleClick - 鼠标中键双击。
  • 无 - 无操作。
  • RightClick - 鼠标右键单击。
  • RightDoubleClick - 鼠标右键双击。
  • WheelClick - 鼠标滚轮旋转。

上面显示的常量取自MSDN

于 2016-02-09T18:13:04.410 回答
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>

你看过http://www.java2s.com/Tutorial/CSharp/0470__Windows-Presentation-Foundation/BindTextBoxsavecommandtoCommandBinding.htm

于 2012-08-02T23:21:49.123 回答