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>
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, 2022Comments
-
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. almost 13 yearsThis would quite great if it did not fire on mouse down, still +1 though for simplicity...
-
Kris almost 13 yearsYeah, MouseBinding can be a bit limited at times. The Hyperlink method I added executes on MouseUp
-
Mark A. Donohoe over 12 yearsAwesomesausage! I just changed it to
LeftDoubleClick
and got exactly what I needed! -
Anup Sharma over 6 yearsYou may also add
MinHeight="0"
to button.