How to a add a command to a WPF TextBlock?
Asked Answered
R

3

66

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?)

Royer answered 9/8, 2011 at 21:57 Comment(0)
C
152

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>
Cordon answered 9/8, 2011 at 23:15 Comment(3)
This would quite great if it did not fire on mouse down, still +1 though for simplicity...Merganser
Yeah, MouseBinding can be a bit limited at times. The Hyperlink method I added executes on MouseUpCordon
Awesomesausage! I just changed it to LeftDoubleClick and got exactly what I needed!Graphics
M
25

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>
Merganser answered 9/8, 2011 at 22:19 Comment(1)
You may also add MinHeight="0" to button.Salespeople
C
0

Well the button would consume your click and the click would not go further to your TextBlock. If you don't need that, that would be one way to do it. You can modify the textblock ControlTemplate, and add the button, giving the button a new ControlTemplate with a transparent RectangleT. A nicer solution would be to use a way to hookup commands to events like EventBehavior and put it on the OnMouseLeftButtonDown event.

Chain answered 9/8, 2011 at 22:4 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.