How to a add a command to a WPF TextBlock?

47,054

Solution 1

You can use a InputBinding.

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

Edit: Hyperlink is probably worth a mention too.

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

Solution 2

You do not make a transparent button over it, you put the TextBlock into it:

<Button>
    <Button.Template>
        <ControlTemplate TargetType="Button">
            <ContentPresenter />
        </ControlTemplate>
    </Button.Template>
    <TextBlock Text="Lorem Ipsum"/>
</Button>
Share:
47,054
Shai UI
Author by

Shai UI

front-end developer in finance. especially html5/javascript/css based apps for mobile/desktop/tablets, node.js on the back-end. my main interests are heavy GUI, 2d/3d, data visualizations. check out my youtube channel: https://www.youtube.com/channel/UCJagBFh6ClHpZ2_EI5a3WlQ

Updated on July 08, 2022

Comments

  • Shai UI
    Shai UI almost 2 years

    I'd like to be able to click a textblock and have it run a Command. Is this possible? (if not do I just somehow make a tranparent button over it or something?)

  • H.B.
    H.B. almost 13 years
    This would quite great if it did not fire on mouse down, still +1 though for simplicity...
  • Kris
    Kris almost 13 years
    Yeah, MouseBinding can be a bit limited at times. The Hyperlink method I added executes on MouseUp
  • Mark A. Donohoe
    Mark A. Donohoe over 12 years
    Awesomesausage! I just changed it to LeftDoubleClick and got exactly what I needed!
  • Anup Sharma
    Anup Sharma over 6 years
    You may also add MinHeight="0" to button.