如何在选中TextBlock中的文本的位置显示弹出按钮

问题描述 投票:2回答:2

我想在我的TextBlock中添加一个弹出按钮,当我在TextBlock中选择文本时,弹出按钮将显示在所选内容中(类似于Microsoft Edge中的阅读模式,当您在阅读模式中选择文本时,将会出现一个弹出窗口显示该词的定义)。但我不知道怎么做。我已经尝试过使用SelectionChanged,但是这个事件传递的参数没有我可以用来设置flyout的位置。那我该怎么办呢?此外,我想知道SelectionFlyout是为了什么?我认为它可以帮助我。这是我的代码:

<TextBlock x:Name="webviewtest" Grid.Row="1" Text="This is a select-flyout test." FontSize="300" IsTextSelectionEnabled="true" >
    <TextBlock.SelectionFlyout>
        <Flyout>
            <TextBlock Text="this is the flyout"></TextBlock>
        </Flyout>
    </TextBlock.SelectionFlyout>
</TextBlock>

当我选择文本时,弹出窗口从未出现过。很明显,我一直在使用它。所以我检查了Microsoft Docs,它说

获取或设置选择文本时显示的弹出按钮,如果未显示弹出按钮,则为null。

我在网上找不到任何关于此的样品。

c# xaml uwp textblock flyout
2个回答
0
投票

这可以通过将TextBlock IsTextSelectionEnabled设置为True并使用MenuFlyout来显示所选文本来实现。

XAML

    <TextBlock x:Name="webviewtest" Text="This is a select-flyout test." FontSize="100"  IsTextSelectionEnabled="True" RightTapped="webviewtest_RightTapped">
        <FlyoutBase.AttachedFlyout>
            <MenuFlyout x:Name="Flyout">
                <MenuFlyout.Items>
                    <MenuFlyoutItem x:Name="FlyItem" Text="">
                    </MenuFlyoutItem>
                </MenuFlyout.Items>
            </MenuFlyout>
        </FlyoutBase.AttachedFlyout>
    </TextBlock>

C#

    private void webviewtest_RightTapped(object sender, RightTappedRoutedEventArgs e)
    {
        TextBlock tb = sender as TextBlock;

        if (tb.SelectedText.Length > 0)
        {
            Item.Text = tb.SelectedText;
        }
        // Show at cursor position
        Flyout.ShowAt(sender as UIElement, e.GetPosition(sender as UIElement));
    }

0
投票

您需要使用RichTextBlock来替换TextBlock,平台是17134和laster。

    <RichTextBlock HorizontalAlignment="Center"
                   VerticalAlignment="Center"
                   IsTextSelectionEnabled="True">
        <RichTextBlock.ContextFlyout>
            <Flyout>
                <TextBlock Text="flyout" />
            </Flyout>
        </RichTextBlock.ContextFlyout>
        <RichTextBlock.SelectionFlyout>
            <Flyout>
                <TextBlock Text="this is the flyout" />
            </Flyout>
        </RichTextBlock.SelectionFlyout>
        <Paragraph>
            welcome to blog.lindexi.com that has many blogs
        </Paragraph>
    </RichTextBlock>

SelectionFlyout与您保持联系。 TextBlock.SelectionFlyout不起作用·问题#452·Microsoft / microsoft-ui-xaml

github中的所有代码

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.