I spent a good deal of time looking through StackOverflow, as well as Google, before asking this question, and couldn’t find anything terribly useful. I’m looking for a guideline on how to load a Menu from a compiled Xaml file, and attach it to a Menu control. I’m a WPF newbie, so please bear with me.
In my page, I have the following Xaml:
<Menu ItemsSource="{Binding MainMenu}">
</Menu>
My view model class currently looks like so:
public class MainWindowViewModel : ViewModelBase
{
public ItemCollection MainMenu { get; set; }
public MainWindowViewModel()
{
Menu m = (Menu)Application.LoadComponent(new Uri("/Assets/Menus/StartupShellMenu.xaml", UriKind.Relative));
MainMenu = m.Items;
}
}
The StartupShellMenu.xaml file looks like so:
<Menu xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<MenuItem Header="_File">
<MenuItem Header="_Open">
<MenuItem.Icon>
<Image Height="16" Width="16" Source="/Assets/Icons/Open.png"/>
</MenuItem.Icon>
</MenuItem>
<Separator/>
<MenuItem Header="E_xit"/>
</MenuItem>
</Menu>
What I’m seeing is that my menu items show up, but as soon as my mouse moves off the menu (I don’t have to click), the menu disappears. Also, the normal keyboard functionality isn’t working; pressing Alt+F doesn’t display the menu, and once shown, the up/down keys don’t work. I’ve tried changing the type of the MainMenu property to an ObservableCollection, but no change. Any thoughts? I’m sure I’m missing something stupid obvious, but I can’t find anything useful in my searches.
Thanks in advance!
This feels like 100% View to me and the ViewModel maybe shouldn’t be involved.
Why are you using the ViewModel at all for this? Are you really allowing for the Menu to be altered at runtime so it is a dynamic menu?
If not, then give the class in your StartupShellMenu.xaml file a class name and then load it.
Then pull it from the ViewModel as it won’t be needed there.
And instead of putting a Menu in your XAML and binding to MainMenu, just add your new StartupShellMenu class directly in the XAML.
If the menu only exists in the View, keep all Menu code 100% in the View.