Search code examples
mauiconverters

.NET MAUI Converter doesn't react/convert after change of value


I'm currently building a .NET MAUI application and want a part of the UI to change the label's text upon change of a boolean value in the corresponding ViewModel.

<Label Text="{x:Binding IsCorrect, Converter={StaticResource IsCorrectToStringConverter}}"
       TextColor="{x:Binding IsCorrect, Converter={StaticResource IsCorrectToTextColorConverter}}"
       FontAttributes="Bold"
       VerticalOptions="Center" />

And here the corresponding IsCorrectToStringConverter:

public class IsCorrectToStringConverter : IValueConverter
{

    public object? Convert(object? value, Type targetType, object? parameter, CultureInfo culture)
    {
        var isCorrect = (bool)value;
        if (isCorrect)
        {
            return "Answer";
        }
        else
        {
            return "Wrong answer";
        }
    }

    public object? ConvertBack(object? value, Type targetType, object? parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

Here is the code of the Answer class incorporating the IsCorrect property:

public class Answer
{
    [Key]
    public int AnswerId { get; set; }
    public int QuestionId { get; set; }
    public string Content { get; set; }
    public bool IsCorrect { get; set; }
    public int? Points { get; set; }
    [NotMapped]
    public bool IsSelected { get; set; }
}

The part of IsCorrectToTextColorConverter is an analogous problem with likely an analogous solution.

I've tried to test, whether the IsCorrect field is in fact changing without prompting change in the UI, which is in fact the case. Therefore, the converter is likely at fault.

Does anybody know a solution or source of this problem?


Solution

  • Thanks to @JonSkeet and @Jason for providing the simple solution. The UI couldn't respond since it was not properly notified.

    The solution was to make the IsCorrect property observable by making the Answer class partial and extended by ObservableObject. After that, the property was marked as an ObservableProperty, which resolved the issue:

    public partial class Answer : ObservableObject
    {
        [Key]
        public int AnswerId { get; set; }
        public int QuestionId { get; set; }
        public string Content { get; set; }
        [ObservableProperty]
        private bool _isCorrect;
        public int? Points { get; set; }
        [NotMapped]
        public bool IsSelected { get; set; }
    }