2012-03-27 58 views
0

我有2個ContextMenus,第二個是從第一個調用的。問題2 ContextMenus

處理程序用於第一(第二創建):

private void MenuItem_Tap(object sender, System.Windows.Input.GestureEventArgs e) 
    { 
     MenuItem mI = (MenuItem)sender; 

     if (mI.Header.ToString() == "England") 
     { 
      cM.Items.Clear(); 
      cM.Items.Add(new MenuItem() { Header = "Barclays PL" }); 
      cM.Items.Add(new MenuItem() { Header = "Championship" }); 
      cM.Items.Add(new MenuItem() { Header = "League 1" }); 
      cM.Items.Add(new MenuItem() { Header = "League 2" }); 
      cM.Items.Add(new MenuItem() { Header = "Conference" }); 
      cM.Tap += MenuItem_Tap1; 
      //if (cM.Parent == null) 
      //{ 
       cM.IsOpen = true; 
      //} 
     } 
    } 

處理程序爲第二:

 private void MenuItem_Tap1(object sender, System.Windows.Input.GestureEventArgs e) 
    { 
     MenuItem mI1 = (MenuItem)sender; 
     if (mI.Header.ToString() == "Barclays PL") 
      this.NavigationService.Navigate(new Uri("/pEng.xaml", UriKind.Relative)); 
    } 

但有System.InvalidCastException在第二處理程序(菜單項MI1 =(菜單項)發送方)。

請幫幫我,怎麼了?

+0

什麼是發件人的類型? (將鼠標懸停在其上並查看類型) – 2012-03-27 20:17:32

+0

ContextMenu。在第一種情況下,好的 – 2012-03-27 20:20:05

回答

2

你安裝的MenuItem_Tap1事件處理程序ContextMenuTap事件,而不是每個MenuItemTap事件。試試這個:

cM.Items.Clear(); 
cM.Items.Add(new MenuItem() { Header = "Barclays PL" }); 
cM.Items.Add(new MenuItem() { Header = "Championship" }); 
cM.Items.Add(new MenuItem() { Header = "League 1" }); 
cM.Items.Add(new MenuItem() { Header = "League 2" }); 
cM.Items.Add(new MenuItem() { Header = "Conference" }); 

foreach(var item in cM.Items) { 
    ((MenuItem)item).Tap += MenuItem_Tap1; 
} 
1

您正在將您的Click活動附加到ContextMenu以及代碼和您的評論中,顯然您想將其附加到MenuItem