dotnet icon indicating copy to clipboard operation
dotnet copied to clipboard

RelayCommand<T> does not work with Enumerations

Open AtomicBlom opened this issue 1 year ago • 1 comments

Describe the bug

If you try to bind an enum to a CommandParameter in UWP, then UWP tends to pass them around the system as the raw type of the enum as opposed to the .net type.

This means that when you bind to it and it fires the CanExecute(object?), that it fails because the type does not match (uint != SortOrder)

Regression

No response

Steps to reproduce

I've provided a bare-bones reproduction here: https://github.com/AtomicBlom/EnumRelayCommandTest

But if you create a blank app, and add a ViewModel based on ObservableObject, something like this:

public partial class MainPageViewModel : ObservableObject
	{
		[RelayCommand]
		private void OnSetSortOrder(SortOrder order)
		{
			Debug.WriteLine($"Sort order set to {order}");
		}
	}

	public enum SortOrder : uint
	{
		Ascending,
		Descending
	}

Then attempt to bind to it.

		<Button Command="{x:Bind ViewModel.SetSortOrderCommand, Mode=OneWay}" Content="Press me">
			<Button.CommandParameter>
				<local:SortOrder>Ascending</local:SortOrder>
			</Button.CommandParameter>
		</Button>

You'll find that it fails

Expected behavior

You should be able to pass an enum as a CommandParameter

Screenshots

No response

IDE and version

VS 2022

IDE version

17.12.4

Nuget packages

  • [ ] CommunityToolkit.Common
  • [ ] CommunityToolkit.Diagnostics
  • [ ] CommunityToolkit.HighPerformance
  • [x] CommunityToolkit.Mvvm (aka MVVM Toolkit)

Nuget package version(s)

8.4.0

Additional context

This error was also observed while attempting to port a UWP application to .net9

Help us help you

Yes, I'd like to be assigned to work on this item

AtomicBlom avatar Feb 01 '25 16:02 AtomicBlom

This is a duplicate of #407. It points to the bug in UWP/XAML (#7633). There is a workaround that can be used, reported in both those issues, by creating a custom MarkupExtension. This allows you to bypass the bug in the XAML compiler and pass the enum value as the correct type.

ZodmanPerth avatar May 08 '25 00:05 ZodmanPerth