I’m trying to pass user controls as pages. I have it working with buttons. When I added a menu with click events it no longer works.
This is the block of code where it figures out which UserControl to Fill into the main layout. This part only uses buttons and does work.
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()]);
}
This Part attempts to use the MenuItems and Buttons, It does not work
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()]);
}
}
Error(s) I Recieve.
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'."}
Any Guidance would be greatly appreciated.
Thanks!
Instead checking the source type like this…
…you can instead check it like this:
Then you can move your variable declarations inside your
ifblocks. So your final code looks like this: