Home > other >  Does two way binding work with object properties in MAUI?
Does two way binding work with object properties in MAUI?

Time:01-08

I'm working on a MAUI project and would like to know if I'm doing something wrong or this simplay isn't possible. I have a simple object with some properties that I bind to the Text property of Entry elements in my XAML using two way binding. The data gets displayed correctly, but it doesn't update when I type into the field. I didn't write the OnPropertyChanged myself as I use the MVVM toolkit, so I'm guessing that could be the problem. Does anyone have any more knowledge on this? The class:

public class RegisterDTO
{
    public string Email { get; set; } = "";
    public string Password { get; set; } = "";
    public string FirstName { get; set; } = "Nejm";
    public string LastName { get; set; } = "";
    public string Country { get; set; } = "";
    public string City { get; set; } = "";
    public DateTime? DateOfBirth { get; set; } = null;
}

The view model utilizing it:

public partial class RegisterPageVM : BaseVM
{
    public RegisterPageVM() {
        Title = "Register";
        dto = new RegisterDTO();
    }

    [ObservableProperty]
    private RegisterDTO dto;
}

Thanks for any help!

CodePudding user response:

One work-around is to declare "proxy" properties in your VM, that manipulate the DTO properties:

// Syntax below assumes VM inherits from `ObservableObject`.
// In question code, that means `BaseVM` inherits from `ObservableObject`.
public string Email {
  get => dto.Email;
  set => SetProperty(dto.Email, value, dto, (d, v) => d.Email = v);
}

See code snippet in ObservableObject / Wrapping a non-observable model for explanation of that SetProperty syntax.

  • Change XAML to use these new properties:
    {Binding Email}, rather than {Binding Dto.Email}.
  • Related