[英]How can I prevent a WP7 context menu from closing after an item has been selected?
我已經將上下文菜單項連接到列表框項中,因此點擊它會更改其狀態。 我需要菜單在選定項目后保持打開狀態,或者需要在菜單關閉后以編程方式重新打開菜單。
我的菜單如下所示:
Some Command 1
Some Command 2
Some Command 3
Inverted
用戶可以點擊“ Inverted
命令,然后點擊其他命令之一,使它們在“反轉模式”下運行,通過數據綁定的菜單如下所示:
Some Command 1
Some Command 2
Some Command 3
Inverted ✔
無法弄清楚如何在點擊后保持菜單打開,我嘗試了不太理想的重新打開菜單方法,如下所示:
private void onCommandInvert(object sender, RoutedEventArgs e)
{
CommandState.Instance.Inverted = !CommandState.Instance.Inverted;
// Open it again.
MenuItem menuItem = (MenuItem)sender;
ContextMenu menu = (ContextMenu)menuItem.Parent;
menu.IsOpen = true;
}
但是這樣做會在menu.IsOpen = true
上引發以下異常menu.IsOpen = true
語句:
A first chance exception of type 'System.InvalidOperationException' occurred in
System.Windows.dll
An unhandled exception of type 'System.InvalidOperationException' occurred in
System.Windows.dll
Additional information: Element is already the child of another element.
我還嘗試了Closed
事件進行以下操作,但發生了相同的異常:
private void onContextMenuClosed(object sender, RoutedEventArgs e)
{
ContextMenu menu = (ContextMenu)sender;
menu.IsOpen = true;
}
有任何想法嗎? 謝謝!
我知道了! 感謝willmel的評論,我瀏覽了MenuItem
的源代碼,並且能夠重寫OnClick()
來精確地執行我需要的操作(毫無疑問是理想的解決方案)。 但是,我無法訪問Click
,因此還需要引入StayClick
事件屬性。
請享用!
using Microsoft.Phone.Controls;
using System.Windows;
namespace MyNamespace
{
public class MenuItemEx : MenuItem
{
public bool StayOpenWhenClicked
{
get;
set;
}
public event RoutedEventHandler StayClick;
protected override void OnClick()
{
if (StayOpenWhenClicked)
{
if (StayClick != null)
{
StayClick.Invoke(this, new RoutedEventArgs());
}
}
else
{
base.OnClick();
}
}
}
}
並在頁面的xaml中,使用my:MenuItemEx
而不是toolkit:MenuItem
my:MenuItemEx
<my:MenuItemEx
Header="Inverted"
StayClick="onCommandInvert"
StayOpenWhenClicked="True"
/>
如果您要在用戶選擇一個項目后保留菜單,那么我相信上下文菜單控件不是您應該使用的菜單控件。
更好的是,您應該創建自己的用戶控件來模仿該行為,並將其適當地放置在有意義的屏幕上(側面或上方/下方)
或者,如果這些是要在選定項目上執行的選項,請考慮使用應用程序欄圖標/菜單項並編寫事件代碼以讀取列表框項目的當前選定值。
希望這可以幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.