如何向WPF TextBlock添加命令?

for*_*yez 62 c# wpf xaml command textblock

我希望能够单击一个文本块并让它运行命令.这可能吗?(如果不是,我只是以某种方式在它上面做一个透明按钮?)

Kri*_*is 134

您可以使用InputBinding.

<TextBlock Text="Hello">
    <TextBlock.InputBindings>
        <MouseBinding Command="" MouseAction="LeftClick" />
    </TextBlock.InputBindings>
</TextBlock>
Run Code Online (Sandbox Code Playgroud)

编辑:超链接也许值得一提.

<TextBlock><Hyperlink Command="" TextDecorations="None" Foreground="Black">Hello</Hyperlink></TextBlock>
Run Code Online (Sandbox Code Playgroud)

  • 哇,你是相当机智的,Hyperlink替代品非常完美...... (3认同)
  • 是的,MouseBinding有时会受到一些限制.我添加的Hyperlink方法在MouseUp上执行 (2认同)
  • Awesomesausage!我刚把它改成了'LeftDoubleClick`并得到了我所需要的! (2认同)

H.B*_*.B. 25

你没有在它上面创建一个透明按钮,你将TextBlock 放入其中:

<Button>
    <Button.Template>
        <ControlTemplate TargetType="Button">
            <ContentPresenter />
        </ControlTemplate>
    </Button.Template>
    <TextBlock Text="Lorem Ipsum"/>
</Button>
Run Code Online (Sandbox Code Playgroud)