如何向WPF TextBlock添加命令?

时间:2011-08-09 21:57:38

标签: c# wpf xaml command textblock

我希望能够单击一个文本块并让它运行一个命令。这可能吗? (如果不是,我只是以某种方式在它上面做一个透明按钮?)

3 个答案:

答案 0 :(得分:131)

您可以使用InputBinding

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

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

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

答案 1 :(得分:25)

你没有在它上面创建透明按钮,你将TextBlock 放入

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

答案 2 :(得分:0)

按钮会消耗您的点击,点击不会进一步发送到TextBlock。如果您不需要,那将是一种方法。您可以修改文本块ControlTemplate,并添加按钮,为按钮提供一个带透明RectangleT的新ControlTemplate。一个更好的解决方案是使用一种方法将命令连接到EventBehavior等事件并将其放在OnMouseLeftButtonDown事件上。