2

Im using the Microsoft Community MVVM package within my MAUI app. It's working well, but I've hit an issue.

Part of my UI modifies a structure which sends a message to the view model. This works fine. However, when I try to modify the structure, I'm getting an exception (Object does not match target type.)

The code leading up to the exception looks like this

messenger.Register<ObjectMessage>(this, (o, t) =>
{
     switch (t.Sender)
     {
          case "Changes":
              try
              {
                   var prop = Content.Structure.GetType().GetProperty((string)t.Message);
                   prop.SetValue(t.Value, Convert.ChangeType(t.Value, prop.PropertyType));
               }
               catch(Exception ex)
               {
 #if DEBUG
                   Console.WriteLine($"Exception - ex.Message = {ex.Message}");
 #endif
               }
               HasChanges = Content.Structure != DupeContent.Structure;
               break;
      }
 });

I've tried a number of different ways to assign the value to the property, but always get the exception.

t.Value and t.Message are of type object

Nodoid
  • 1,449
  • 3
  • 24
  • 42
  • `t.Value` and `t.Message` are of type `object` - This isn't a helpful statement because `object` is [an alias for System.Object](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/reference-types), and ["all classes in .NET are derived from Object"](https://learn.microsoft.com/en-us/dotnet/api/system.object?view=net-7.0). What do you get when you do `t.Value.GetType()` or `t.Message.GetType()`? – Chuck Jan 20 '23 at 17:30
  • Is the error occurring in `Convert.ChangeType` or in `SetValue`? If necessary, split into two separate statements to isolate the problem. – ToolmakerSteve Jan 20 '23 at 20:52

1 Answers1

2

The first argument to SetValue should be the actual object you're trying to modify. In this case, it appears to be Content.Structure (since that's what you called GetType() on). Try using that object as the first argument:

prop.SetValue(Content.Structure, Convert.ChangeType(t.Value, prop.PropertyType));
Rufus L
  • 36,127
  • 5
  • 30
  • 43