如何使 TextBlock 可选,以便用户可以复制其文本 [英] How can I make TextBlock as selectable so that user can copy its text

查看:35
本文介绍了如何使 TextBlock 可选,以便用户可以复制其文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能的重复:
有什么方法可以使 WPF 文本块可选?

我可以在 WPF 应用程序中选择一个文本块,以便用户可以复制它吗.

Can I make a textblock selectable in WPF application so that a user can copy it.

提前致谢.

DJ

推荐答案

你可以把它变成一个只读的 TextBox,它看起来像一个 TextBlock,有点像;

You could just make it into a TextBox that's Read Only which just looks like a TextBlock, kind of like;

<Style x:Key="ReadOnlyTextBox" TargetType="TextBox">
   <Setter Property="IsReadOnly" Value="True" />
   <Setter Property="Padding" Value="5"/>
   <Setter Property="Margin" Value="0"/>
   <Setter Property="Background" Value="Transparent"/>
   <Setter Property="BorderBrush" Value="Transparent"/>
   <Setter Property="BorderThickness" Value="0"/>
   <Setter Property="IsTabStop" Value="False"/>
   <Setter Property="HorizontalScrollBarVisibility" Value="Disabled"/>
   <Setter Property="VerticalScrollBarVisibility" Value="Disabled"/>
   <Setter Property="Template">
      <Setter.Value>
         <ControlTemplate TargetType="TextBox">
            <Grid x:Name="RootElement">
               <ScrollViewer x:Name="ContentElement"
                             Margin="{TemplateBinding Margin}"
                             Background="{TemplateBinding Background}"
                             BorderBrush="{TemplateBinding BorderBrush}"
                             BorderThickness="{TemplateBinding BorderThickness}"
                             IsTabStop="{TemplateBinding IsTabStop}"
                             Padding="{TemplateBinding Padding}" 
                             HorizontalScrollBarVisibility="{TemplateBinding HorizontalScrollBarVisibility}"
                             VerticalScrollBarVisibility="{TemplateBinding VerticalScrollBarVisibility}"/>
            </Grid>
         </ControlTemplate>
      </Setter.Value>
   </Setter>
</Style>

默认情况下,ScrollViewer ContentElement 将位于 TextBox 中,如果您愿意,也可以替换为 ContentPresenter.

The ScrollViewer ContentElement would be in a TextBox by default, you could substitute for a ContentPresenter instead if you like also.

然后生效;

<TextBox Text="Blah Blah Blah you can copy me!" Style="{StaticResource ReadOnlyTextBox}"/>

希望这有帮助!

附录: 正如@doodleus 在评论中指出的那样.可能需要在模板中绑定内容属性的模板.因为ContentElement"是 Silverlight TextBox 控件的命名部分.在不同的 xaml 变体中需要注意的细微差别之一.当我最初创建示例时,我一定没有注意标签.非常感谢他纠正我.

ADDENDUM: As @doodleus pointed out in the comments. Template binding the Content Property within the template may be necessary. As "ContentElement" is a named part of the Silverlight TextBox control. One of the little nuance differences to watch for in the different xaml Variants. I must not have paid attention to the Tags when I originally created the example. So kudos to him for correcting me.

这篇关于如何使 TextBlock 可选,以便用户可以复制其文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆