【问题标题】:How to a add a command to a WPF TextBlock?如何向 WPF TextBlock 添加命令?
【发布时间】:2011-10-23 15:04:54
【问题描述】:

我希望能够单击文本块并让它运行命令。这可能吗? (如果不是我只是以某种方式在它上面制作一个透明按钮或其他什么?)

【问题讨论】:

    标签: c# wpf xaml command textblock


    【解决方案1】:

    您可以使用InputBinding

    <TextBlock Text="Hello">
        <TextBlock.InputBindings>
            <MouseBinding Command="" MouseAction="LeftClick" />
        </TextBlock.InputBindings>
    </TextBlock>
    

    编辑:超链接可能也值得一提。

    <TextBlock><Hyperlink Command="" TextDecorations="None" Foreground="Black">Hello</Hyperlink></TextBlock>
    

    【讨论】:

    • 如果它没有在鼠标按下时触发,那就太好了,尽管为了简单起见仍然 +1...
    • 是的,MouseBinding 有时会受到一些限制。我添加的超链接方法在 MouseUp 上执行
    • 棒极了!我只是将其更改为LeftDoubleClick 并得到了我需要的东西!
    【解决方案2】:

    你没有在它上面做一个透明按钮,你把 TextBlock 放入它:

    <Button>
        <Button.Template>
            <ControlTemplate TargetType="Button">
                <ContentPresenter />
            </ControlTemplate>
        </Button.Template>
        <TextBlock Text="Lorem Ipsum"/>
    </Button>
    

    【讨论】:

    • 您也可以在按钮上添加MinHeight="0"
    【解决方案3】:

    那么按钮会消耗您的点击,并且点击不会进一步到达您的TextBlock。如果您不需要它,那将是一种方法。您可以修改文本块 ControlTemplate,并添加按钮,为按钮提供一个带有透明 RectangleT 的新 ControlTemplate。更好的解决方案是使用一种方法将命令连接到 EventBehavior 之类的事件,并将其放在 OnMouseLeftButtonDown 事件上。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-06-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-30
      • 1970-01-01
      • 2013-06-22
      相关资源
      最近更新 更多