0

I am switching from Qt to WPF and what I want is to create a simple application containing both menu bar and toolbar. All commands are present in the menu bar and some of them are accessible also from the toolbar. Also I want to assign some icons to the commonly used commands and display them in both menu and toolbar.

I defined several custom commands in the code-behind file and now I am dealing with the XAML file. When I want to define a single menu item with icon, I have to write something like

<Window.Resources>
    <BitmapImage x:Key="Connect" UriSource="Resources/connect.png" />
<Window.Resources>
...
<Menu>
    <MenuItem Command="local:Commands.Connect">
        <MenuItem.Icon>
            <Image Source="{StaticResource Connect}" Width="16" />
        </MenuItem.Icon>
    </MenuItem>
</Menu>

The tool button for a single command is even more demanding:

<ToolBar>
    <Button Command="local:Commands.Connect" >
        <StackPanel Orientation="Horizontal">
            <Image Source="{StaticResource Connect}" Width="32" />
            <TextBlock Text="Connect..." VerticalAlignment="Center" /> 
        </StackPanel>
    </Button>        
</ToolBar>

The code works, but in my opinion it is too bloated and confusing for higher amount of commands. I tried to play with ControlTemplate, but the TemplateBinding is quite limiting since it can use only existing attributes of the controls...

Is there a way how to make the XAML definitions shorter and more reusable? E.g. to make a template and then create each menu item with a single line of code?

klasyc
  • 569
  • 6
  • 23
  • Xaml is verbose. Is your question about how to organize icons or what? I'd say start with the [vector graphics](https://stackoverflow.com/q/3526366/1997232). – Sinatr Jan 29 '20 at 16:09
  • I had this same problem. A large application's toolbar can result in huge and repetitive XAML. Styles can help, but to really reduce bloat I ended up using MVVM and creating ViewModels for my menus and menu items. Then you can just use `DataTemplate` for each type of command ViewModel you have and bind the menu to your collection of ViewModels. Here is an example of someone doing just that https://stackoverflow.com/questions/23941314/wpf-how-can-i-create-menu-and-submenus-using-binding – Jason Tyler Jan 29 '20 at 16:17
  • @Sinatr: I modified the end of the question to make it clear. – klasyc Jan 29 '20 at 16:35
  • @klasyc a `Menu` is just another kind of `ItemsControl`. Simply do ` and use `ItemTemplate` to define what each item looks like – Federico Berasategui Jan 29 '20 at 18:03

0 Answers0