文本块和标签 wpf 上的文本选择

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34724412/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 13:37:13  来源:igfitidea点击:

Text selection on textblock and label wpf

c#.netwpfxaml

提问by daewoosh

I have a form, which includes TextBlocks, Lables, Borders. And I want to be able to select text with the mouse like it would be some text in the table in MS Word or HTML table. And I can't use TextBox or RichTextBox instead. Is there a way to achive my goal?

我有一个表单,其中包括 TextBlocks、Lables、Borders。我希望能够用鼠标选择文本,就像在 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>

回答by Mohammed A. Fadil

Use TextBox instead of a TextBlock, like the following code:

使用 TextBox 而不是 TextBlock,就像下面的代码:

<TextBox
     Background="Transparent"
     TextWrapping="Wrap"
     Text="{Binding Desired, Mode=OneWay}"
     IsReadOnly="True"
     BorderThickness="0"/>

To make it cleaner, careate a template for the TextBlock and use the previous TextBox inside it.

为了使它更干净,请为 TextBlock 设计一个模板并在其中使用以前的 TextBox。

回答by David ?karda

You can achieve it like this:

你可以这样实现:

<TextBlock Text="test2"
           FontSize="16"
           IsTextSelectionEnabled="true"
           SelectionHighlightColor="Green"
           x:Name="test"      
           Foreground="Black"
           TextWrapping="Wrap"
           TextAlignment="Left"/>

Just set IsTextSelectionEnabledto true. You can also chagne color of selected text by changing SelectionHighlightColorproperty.

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