如何通过右键单击从窗口引出用户控制方法?

时间:2015-10-12 11:06:07

标签: c# wpf

我希望在MainWindow中右键单击时,MenuUserControl中的ToggleIsCollapsed()方法会引发。我想用它作为快捷键来点击MenuUserControl中的按钮。

我有这样的用户控件:

public partial class MenuUserControl : UserControl
{
    public MenuUserControl()
    {
        InitializeComponent();
    }

    public static readonly RoutedEvent ClickEvent = EventManager.RegisterRoutedEvent("Click", RoutingStrategy.Bubble, typeof(RoutedEventHandler), typeof(MenuUserControl));

    public event RoutedEventHandler Click
    {
        add { AddHandler(ClickEvent, value); }
        remove { RemoveHandler(ClickEvent, value); }
    }

    void RaiseClickEvent()
    {
        RoutedEventArgs newEventArgs = new RoutedEventArgs(ClickEvent);
        RaiseEvent(newEventArgs);
    }

    public bool IsCollapsed
    {
        get { return (bool)GetValue(IsCollapsedProperty); }
        set { SetValue(IsCollapsedProperty, value); }
    }

    // Using a DependencyProperty as the backing store for IsCollapsed.  This enables animation, styling, binding, etc...
    public static DependencyProperty IsCollapsedProperty = DependencyProperty.Register("IsCollapsed", typeof(bool), typeof(MenuUserControl), new PropertyMetadata(false));

    public void ToggleIsCollapsed()
    {
        IsCollapsed = !IsCollapsed;
    }

    private void CollapseButton_Click(object sender, RoutedEventArgs e)
    {
        RaiseClickEvent();
    }
}

和像这样的MainWindow:

public partial class MainWindow : WindowBase
{
    public MainWindow()
    {
        InitializeComponent();
        AddHandler(MenuUserControl.ClickEvent, new RoutedEventHandler(Click));
    }

    private void Click(object sender, RoutedEventArgs e)
    {
       // MenuUserControl.ToggleIsCollapsed();
    }

    private void WindowBase_PreviewMouseRightButtonDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
    {

    }
}
你帮我吗?提前谢谢!

1 个答案:

答案 0 :(得分:2)

使用MouseRightButtonDown事件抓住鼠标右键。

public MainWindow()
{
    InitializeComponent();
    this.MouseRightButtonDown += MainWindow_MouseRightButtonDown;
}

private void MainWindow_MouseRightButtonDown(object sender, MouseButtonEventArgs e)
{
    MenuUserControl.ToggleIsCollapsed();
}

public partial class MenuUserControl
{
    public static void ToggleIsCollapsed()
    {
        // do your stuff
    }
}

您在评论中描述的错误是因为您尝试从静态方法(IsCollapsed)调用非静态方法(ToggleIsCollapsed)。您有两种选择:

使IsCollapsed静态:

public static bool IsCollapsed
{
    get { return (bool)GetValue(IsCollapsedProperty); }
    set { SetValue(IsCollapsedProperty, value); }
}

或者ToggleIsCollapsed非静态:

public void ToggleIsCollapsed()
{
    // do your stuff
}

请注意,如果您使ToggleIsCollapsed为非静态,则必须创建MenuUserControl类的新实例。否则你将得到与以前相同的错误:

private void MainWindow_MouseRightButtonDown(object sender, MouseButtonEventArgs e)
{
    // new instance of class
    MenuUserControl usrCtrl = new MenuUserControl();
    usrCtrl.ToggleIsCollapsed();
}