[英]modifying TextBox context menu/MenuFlyout
我尝试使用此代码修改 TextBox 上下文菜单/MenuFlyout,但它不起作用(不会出现附加菜单项并且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"/>
问题是您没有为SelectionFlyout
或ContextFlyout
提供MenuFlyout
实例。 请参考以下代码添加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)
{
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.