c# - 如何在选择 TextBlock 中的文本的位置显示弹出窗口

标签 c# xaml uwp textblock flyout

我想向我的 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它说

Gets or sets the flyout that is shown when text is selected, or null if no flyout is shown.

而且我在网上找不到任何关于此的示例。

最佳答案

这可以通过将 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));
    }

关于c# - 如何在选择 TextBlock 中的文本的位置显示弹出窗口,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55138073/

相关文章:

c# - 我如何将 ORM 用于架构在运行时之前未知的数据库?

c# - 在 ZeroMQ C# 中断开套接字

XAML 中的 WPF 日期时间。如何添加天数?

c# - WPF 中 UIElement 的核心属性是什么?

uwp - 如何从后台线程获取 UWP 应用程序的当前 View ?

c# - UWP获取国家/地区电话号码前缀

c# - UWP (Windows 10) 后台任务 - 错误 HRESULT E_FAIL 已从对 COM 组件的调用返回 (VS2017)

c# - WPF - 在文本框外部单击时移除焦点

c# - "Items collection cannot be modified when the DataSource property is set."

c# - 媒体引擎错误,在本地机器上听不到声音