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