如何向WPF TextBlock添加命令?

66

我希望能够点击文本块并运行命令。这是否可能? (如果不行,我是否需要在其上创建一个透明按钮或其他东西?)

3个回答

151

您可以使用 InputBinding

<TextBlock Text="Hello">
    <TextBlock.InputBindings>
        <MouseBinding Command="" MouseAction="LeftClick" />
    </TextBlock.InputBindings>
</TextBlock>

编辑:超链接也值得一提。

<TextBlock><Hyperlink Command="" TextDecorations="None" Foreground="Black">Hello</Hyperlink></TextBlock>

1
如果它不在鼠标按下时触发,那就非常好了,尽管由于简单性而+1... - H.B.
2
是的,MouseBinding 有时可能会受到一定的限制。我添加的 Hyperlink 方法在 MouseUp 上执行。 - Kris
2
太棒了!我刚把它改成LeftDoubleClick,得到了我需要的东西! - Mark A. Donohoe

25

你不需要在它上面制作透明按钮,而是将文本块放入其中:

<Button>
    <Button.Template>
        <ControlTemplate TargetType="Button">
            <ContentPresenter />
        </ControlTemplate>
    </Button.Template>
    <TextBlock Text="Lorem Ipsum"/>
</Button>

您还可以在按钮中添加 MinHeight="0" - Anup Sharma

0

好的,按钮会消耗你的点击事件,而且点击事件不会传递到你的TextBlock。如果你不需要这个功能,那么这是一种方法。你可以修改textblock控件模板,并添加按钮,给按钮一个新的控件模板,其中包含一个透明的RectangleT。更好的解决方案是使用一种将命令连接到事件的方法,例如EventBehavior,并将其放在OnMouseLeftButtonDown事件上。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接