Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to a add a command to a WPF TextBlock?

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

like image 343
Shai UI Avatar asked Aug 09 '11 21:08

Shai UI


People also ask

What is command binding in WPF?

The command is the action to be executed. The command source is the object which invokes the command. The command target is the object that the command is being executed on. The command binding is the object which maps the command logic to the command.

Is TextBlock editable?

TextBlock is not editable.

How do I create a line break in TextBlock WPF?

Adding Line Breaks Sometimes you will want to insert a line break within a TextBlock. You can do this with a LineBreak inline, added as an XAML element within the text. A new line will be started at the position of this element.


2 Answers

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> 
like image 179
Kris Avatar answered Sep 22 '22 11:09

Kris


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> 
like image 24
H.B. Avatar answered Sep 21 '22 11:09

H.B.