菜单项和问题的问题按钮事件

时间:2012-01-24 20:06:24

标签: c# wpf menuitem

我正在尝试将用户控件作为页面传递。我有按钮使用它。当我添加一个包含点击事件的菜单时,它不再有效。

这是代码块,它指出要填充到主布局中的UserControl。这部分只使用按钮并且有效。

private void btnGeneral_Click(object sender, RoutedEventArgs e)
    {
        PanelMainContent.Children.Clear();
        Button button = (Button)e.OriginalSource;
        PanelMainWrapper.Header = button.Content;
        Type type = this.GetType();
        Assembly assembly = type.Assembly;
        PanelMainContent.Children.Add(_userControls[button.Tag.ToString()]);
    }

本部分尝试使用MenuItems和Buttons,它不起作用

public void btnGeneral_Click(object sender, RoutedEventArgs e)
    {   

        PanelMainContent.Children.Clear();
        MenuItem menuItem = (MenuItem)e.OriginalSource;
        Button button = (Button)e.OriginalSource;

        if (e.OriginalSource == menuItem)
        {
            PanelMainWrapper.Header = menuItem.Header;
            Type type = this.GetType();
            Assembly assembly = type.Assembly;
            PanelMainContent.Children.Add(_userControls[menuItem.Tag.ToString()]);
        }

        if (e.OriginalSource == button)
        {
            PanelMainWrapper.Header = button.Content;
            Type type = this.GetType();
            Assembly assembly = type.Assembly;
            PanelMainContent.Children.Add(_userControls[button.Tag.ToString()]);
        }
    }

我收到的错误。

XamlParseException:
The invocation of the constructor on type 'Test.MainWindow' that matches the specified    binding constraints threw an exception.' Line number '5' and line position '9'

InnerException
{"Unable to cast object of type 'System.Windows.Controls.Button' to type 'System.Windows.Controls.MenuItem'."}

任何指导都将不胜感激。

谢谢!

2 个答案:

答案 0 :(得分:3)

您正在尝试将Button转换为MenuItem

MenuItem menuItem = (MenuItem)e.OriginalSource;
Button button = (Button)e.OriginalSource;

我忘记了它的确切术语,但是这样投射:

MenuItem menuItem = e.OriginalSource as MenuItem;
Button button = e.OriginalSource as Button;

如果正在转换的对象不是预期类型,则此方法将返回null,并且不会抛出异常。在尝试使用它们之前,请确保您测试的menuItembutton变量不是null

答案 1 :(得分:2)

而是像这样检查源类型......

if (e.OriginalSource == menuItem)

...你可以这样检查:

if(e.OriginalSource is MenuItem)

然后,您可以在if块内移动变量声明。所以你的最终代码如下:

public void btnGeneral_Click(object sender, RoutedEventArgs e)
{   
    PanelMainContent.Children.Clear();

    if (e.OriginalSource is MenuItem)
    {
        MenuItem menuItem = (MenuItem)e.OriginalSource;
        PanelMainWrapper.Header = menuItem.Header;
        Type type = this.GetType();
        Assembly assembly = type.Assembly;
        PanelMainContent.Children.Add(_userControls[menuItem.Tag.ToString()]);
    }

    if (e.OriginalSource is Button)
    {
        Button button = (Button)e.OriginalSource;
        PanelMainWrapper.Header = button.Content;
        Type type = this.GetType();
        Assembly assembly = type.Assembly;
        PanelMainContent.Children.Add(_userControls[button.Tag.ToString()]);
    }
}