Skip to content

Generated MenuItems cannot bind to commands or methods with strongly typed parameters with inline style #9372

@stevemonaco

Description

@stevemonaco

Describe the bug
When generating MenuItems from Items with an inline style, a binded command with a parameter will throw an exception if the RelayCommand<T> is not of type object. Binding to a method with a strong type (not object) will show a disabled menu parent with no child items. Method binding issue may be related to #8905.

To Reproduce
Full repro with multiple scenarios

<MenuItem Header="Recent Files" Items="{Binding RecentFiles}">
	<MenuItem.Styles>
		<Style Selector="MenuItem">
			<Setter Property="Command" Value="{ReflectionBinding #menu.DataContext.OpenRecentFileWithStringCommand}" />
			<Setter Property="CommandParameter" Value="{Binding}" />
			<Setter Property="Header" Value="{Binding}" />
		</Style>
	</MenuItem.Styles>
</MenuItem>

RecentFiles is an ObservableCollection<string>

image

MenuItem.TryUpdateCanExecute is the last Avalonia location of the crash. Mvvm Toolkit ends with a CanExecute and ThrowArgumentExceptionForInvalidCommandArgument. This scenario works when I change to RelayCommand<object> and cast the parameter to string.

Alternatively, applying a top-level selector instead of inline does work with strongly typed parameters:

<!-- Top-level selector handling everything -->
<Style Selector="MenuItem.recentCommand > MenuItem">
	<Setter Property="Header" Value="{Binding}" />
	<Setter Property="CommandParameter" Value="{Binding}" />
	<Setter Property="Command" Value="{ReflectionBinding #menu.DataContext.OpenRecentFileWithStringCommand}" />
</Style>
...
<MenuItem Header="StringCommand.recentCommand">
	<MenuItem Classes="recentCommand" Header="Recent Files" Items="{Binding RecentFiles}" />
</MenuItem>

Expected behavior
I expect to bind to commands with strongly typed parameters. T is string in the repro. The inline style approach was mentioned in other issues about dynamic menu generation as well as the docs.

Desktop (please complete the following information):

  • OS: Win10
  • Version: 0.10.18 and 11-preview3

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions