Text selection on textblock and label wpf

3

我有一个表单,其中包括文本块、标签和边框。我想要能够像在MS Word或HTML表格中选择文本一样使用鼠标选择文本。但我不能使用TextBox或RichTextBox。有没有办法实现我的目标?

<Grid Margin="20">
<Grid.RowDefinitions>
    <RowDefinition Height="auto"/>
    <RowDefinition Height="auto"/>
</Grid.RowDefinitions>
<Border BorderBrush="Black" BorderThickness="1">
    <StackPanel Orientation="Horizontal">
        <TextBlock Text="some text in TextBlock" VerticalAlignment="Center"/>
        <Label Content="another text in Label"/>
    </StackPanel>
</Border>
<Border Grid.Row="1" BorderBrush="Black" BorderThickness="1">
    <StackPanel Orientation="Horizontal">
        <TextBlock Text="one more  in TextBlock" VerticalAlignment="Center"/>
        <Label Content="one more text in Label"/>
    </StackPanel>
</Border>


2
你不能使用带样式的 TextBox 吗?例如: https://dev59.com/Y3VC5IYBdhLWcg3w9GHM 或者 http://geekswithblogs.net/mhildreth/archive/2008/06/25/selectable-labels-in-wpf-to-allow-copy-and-paste.aspx,有特殊原因吗? - Arie
2
您可以使用具有“IsReadOnly ="True"”属性的 TextBox,而不是使用 TextBlock 实现此目的。 - Salah Akbari
2
刚想问同样的事情。 - Chris W.
1
使用只读文本框,然后像这里一样呈现它,就像标签一样。 - Kurt Van den Branden
请澄清一下...您是想选择文本块和标签中的文本,还是只在一个控件内选择? - grek40
@grek40,也许我可以使用文本框...但它只允许我选择一个控件中的文本,而我需要选择所有文本或其中一部分。就像在网页上一样。在网页上,我可以随意选择任何我想要的内容。 - daewoosh
2个回答

3
请使用TextBox而不是TextBlock,如下代码所示:
<TextBox
     Background="Transparent"
     TextWrapping="Wrap"
     Text="{Binding Desired, Mode=OneWay}"
     IsReadOnly="True"
     BorderThickness="0"/>

为了使其更加简洁,创建一个 TextBlock 模板,并在其中使用之前的 TextBox。

-2
你可以像这样实现它:
<TextBlock Text="test2"
           FontSize="16"
           IsTextSelectionEnabled="true"
           SelectionHighlightColor="Green"
           x:Name="test"      
           Foreground="Black"
           TextWrapping="Wrap"
           TextAlignment="Left"/>

只需将IsTextSelectionEnabled设置为true即可。 您还可以通过更改SelectionHighlightColor属性来更改所选文本的颜色。


你不能在Win7中使用它,正如这里所写的一样(我可以确认这一点)。 - Massimiliano Kraus
在Windows 10上使用Visual Studio 2015,无法看到TextBlock的这些属性。 - Yoav Feuerstein
1
无法看到这些属性,同时在 Windows 10 上运行 Visual Studio 2015。 - hegu_141

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接