菜单项的问题&;按钮事件

本文关键字:按钮 事件 amp 问题 菜单项 | 更新日期: 2023-09-27 18:21:14

我正试图将用户控件作为页面传递。我用按钮操作它。当我添加了一个带有点击事件的菜单时,它就不再工作了。

这是一个代码块,用于确定要填充到主布局中的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()]);
    }

这部分试图使用菜单项和按钮,它不工作

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'."}

如有任何指导意见,我们将不胜感激。

谢谢!

菜单项的问题&;按钮事件

您正试图在此处将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

不要像这样检查源类型。。。

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()]);
    }
}