How to a add a command to a WPF TextBlock?

前端 未结 3 1832
予麋鹿
予麋鹿 2020-12-24 00:40

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

相关标签:
3条回答
  • 2020-12-24 00:50

    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.

    0 讨论(0)
  • 2020-12-24 00:53

    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>
    
    0 讨论(0)
  • 2020-12-24 01:12

    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>
    
    0 讨论(0)
提交回复
热议问题