2010-09-30 121 views
5

嗨 我试图摆脱恼人的“关于Silverlight”上下文菜单,每当您右键单击Silverlight应用程序时弹出。我已经添加了通常的方法:禁用在组合框中右键单击“Silverlight”弹出框

在App.xaml中
rootVisual.MouseRightButtonDown + =((S,参数)=> args.Handled = TRUE);

和所有ChildWindows都一样。 持续存在的问题是所有“弹出” - 控制像组合框和日期选择器日历弹出。在那里我无法摆脱它。我想以一种我可以隐含的方式处理整个应用程序的右键单击。这可能吗?我能解决一些其他的智能方式吗?

最佳
丹尼尔

回答

6

答案是继承组合框,让这样一个自定义的控制:

public class CellaComboBox : ComboBox 
{ 
    public CellaComboBox() 
    { 
     DropDownOpened += _dropDownOpened; 
     DropDownClosed += _dropDownClosed; 
    } 

    private static void _dropDownClosed(object sender, EventArgs e) 
    { 
     HandlePopupRightClick(sender, false); 
    } 

    private static void _dropDownOpened(object sender, EventArgs e) 
    { 
     HandlePopupRightClick(sender, true); 
    } 

    private static void HandlePopupRightClick(object sender, bool hook) 
    { 
     ComboBox box = (ComboBox)sender; 
     var popup = box.GetChildElement<Popup>(); 
     if (popup != null) 
     { 
      HookPopupEvent(hook, popup); 
     } 
    } 

    static void HookPopupEvent(bool hook, Popup popup) 
    { 
     if (hook) 
     { 
      popup.MouseRightButtonDown += popup_MouseRightButtonDown; 
      popup.Child.MouseRightButtonDown += popup_MouseRightButtonDown; 
     } 
     else 
     { 
      popup.MouseRightButtonDown -= popup_MouseRightButtonDown; 
      popup.Child.MouseRightButtonDown -= popup_MouseRightButtonDown; 
     } 
    } 


    static void popup_MouseRightButtonDown(object sender, System.Windows.Input.MouseButtonEventArgs e) 
    { 
     e.Handled = true; 
    } 

与framworkelement的扩展方法看起来像这样的:

public static class FrameworkElementExtensions 
{ 
    public static TType GetChildElement<TType>(this DependencyObject parent) where TType : DependencyObject 
    { 
     TType result = default(TType); 

     if (parent != null) 
     { 
      result = parent as TType; 

      if (result == null) 
      { 
       for (int childIndex = 0; childIndex < VisualTreeHelper.GetChildrenCount(parent); ++childIndex) 
       { 
        var child = VisualTreeHelper.GetChild(parent, childIndex) as FrameworkElement; 
        result = GetChildElement<TType>(child) as TType; 
        if (result != null) return result; 
       } 
      } 
     } 

     return result; 
    } 
} 

你需要处理的DatePicker以同样的方式,但不是DropDownOpened和DropDownClosed您使用CalenderOpened和CalenderClosed

+1

不需要创建自定义类。附加的行为工作得很好。 – SergioL 2011-03-02 21:45:16

+0

+1:这是一个奇妙的解决方案。描述得很好。在SL AutocompleteComboBox上使用效果相同。 – 2012-11-15 13:14:44

2

C#角落都有对Silverlight 3的固定约弹出的文章:

Disable Context Menu in Silverlight 3 Application

+1

感谢您的答复。如果您在浏览器中运行应用程序,此解决方案完美工作。不幸的是,这个修复程序消除了应用程序的OOB可能性,而OOB是客户的先决条件。 – 2010-11-04 13:14:26