修改 TextBox 上下文菜单/MenuFlyout
Posted
技术标签:
【中文标题】修改 TextBox 上下文菜单/MenuFlyout【英文标题】:modifying TextBox context menu/MenuFlyout 【发布时间】:2020-04-20 10:03:57 【问题描述】:我尝试使用此代码,但它不起作用(额外的菜单项不出现,myFlyout
总是 null
)(UWP/C#)
private void Menu_Opening(object sender, object e)
MenuFlyout myFlyout = sender as MenuFlyout;
if (myFlyout != null && myFlyout.Target == TextBox)
MenuFlyoutSubItem searchWith = new MenuFlyoutSubItem();
searchWith.Icon = new SymbolIcon(Symbol.Find);
searchWith.Text = "Search With";
MenuFlyoutItem googles = new MenuFlyoutItem();
googles.Text = "Google";
googles.Click += Googles_Click;
searchWith.Items.Add(googles);
MenuFlyoutItem bings = new MenuFlyoutItem();
bings.Text = "Bing";
bings.Click += Bings_Click;
searchWith.Items.Add(bings);
myFlyout.Items.Add(searchWith);
private async void Googles_Click(object sender, RoutedEventArgs e)
if (TextBox.SelectedText != null)
var uri= new Uri(@"https://google.com/search?q=" + TextBox.SelectedText);
var success = await Launcher.LaunchUriAsync(uri);
private async void Bings_Click(object sender, RoutedEventArgs e)
if (TextBox.SelectedText != null)
var uri = new Uri(@"https://bing.com/search?q=" + TextBox.SelectedText);
var success = await Launcher.LaunchUriAsync(uri);
private void TextBox_Loaded(object sender, RoutedEventArgs e)
TextBox.SelectionFlyout.Opening += Menu_Opening;
TextBox.ContextFlyout.Opening += Menu_Opening;
private void TextBox_Unloaded(object sender, RoutedEventArgs e)
TextBox.SelectionFlyout.Opening -= Menu_Opening;
TextBox.ContextFlyout.Opening -= Menu_Opening;
<TextBox x:Name="TextBox" Loaded="TextBox_Loaded" Unloaded="TextBox_Unloaded"/>
【问题讨论】:
能分享一下相关的xaml代码吗? @NicoZhu-MSFT 我把它添加到我的问题中 【参考方案1】:问题是您没有将MenuFlyout
实例提供给SelectionFlyout
或ContextFlyout
。请参考以下代码添加MenuFlyout
。
<TextBox x:Name="TextBox" Loaded="TextBox_Loaded" Unloaded="TextBox_Unloaded">
<TextBox.ContextFlyout>
<MenuFlyout>
</MenuFlyout>
</TextBox.ContextFlyout>
</TextBox>
更新
SelectionFlyout
的默认类型是TextCommandBarFlyout
,如果你不想替换默认类型,它不能转换为MenuFlyout
。你可以像下面这样添加TextCommandBarFlyout
,
private void Menu_Opening(object sender, object e)
TextCommandBarFlyout myFlyout = sender as TextCommandBarFlyout;
if (myFlyout != null && myFlyout.Target == TextBox)
AppBarButton searchCommandBar = new AppBarButton() Icon = new SymbolIcon(Symbol.Find), Label = "Search With" ;
searchCommandBar.Click += SearchCommandBar_Click;
myFlyout.PrimaryCommands.Add(searchCommandBar);
private void SearchCommandBar_Click(object sender, RoutedEventArgs e)
【讨论】:
但这会删除内置的上下文菜单 我想修改上下文菜单而不是替换它 谢谢,但是你知道如何让用户在上下文菜单中选择他想要搜索的搜索引擎吗? 根据我的经验,您需要使用本地设置记录选择的引擎,并在调用搜索api时获取选项。以上是关于修改 TextBox 上下文菜单/MenuFlyout的主要内容,如果未能解决你的问题,请参考以下文章
如何将上下文菜单项添加到FlowDocumentScrollViewer内的textBox