EN VI

C# - Binding properties on Picker with .NET MAUI MVVM?

2024-03-12 03:00:04
How to C# - Binding properties on Picker with .NET MAUI MVVM

So currently i have a picker in my contentPage with multiple Areas that come from a datasource "Patio", however i'm trying to validate if the user has selected or not a value in this picker in my ViewModel but i cannot for the life of me figure out why the binding of the selectedItem is not working properly.

Here is my Picker with the bindings, both ItemDisplayBinding and ItemsSource are working fine:

<Picker
    x:Name="pckArea"
    Title="Área"
    FontAttributes="Bold"
    FontSize="Small"
    HorizontalTextAlignment="Start"
    ItemDisplayBinding="{Binding Area}"
    ItemsSource="{Binding Patio}"
    SelectedItem="{Binding SelectedArea}"
    TextColor="Black" />

Below is part of my ViewModel with the SelectedArea property and the validation i'm trying to do, whenever i change the selected item the PropertyChanged event does not seem to trigger and the value of SelectedArea is always null.

[ObservableProperty]
private ObservableCollection<Patio> _patio = new();
[ObservableProperty, NotifyPropertyChangedFor(nameof(CanPost))]
private string _selectedArea;        
// Validations
public bool CanPost => !string.IsNullOrEmpty(EntryChassi)
    && !string.IsNullOrEmpty(Cracha)
    && !string.IsNullOrEmpty(SelectedArea);

Am i doing something just completely wrong here?

I'm relatively new to MAUI and MVVM and also this is my first time posting so if i need to provide more information about the code please just let me know.

Ive also tried doing it this way but it didn't work also:

public string SelectedArea
{
    get => _selectedArea;
    set
    {
        if (_selectedArea != value)
        {
            _selectedArea = value;
            OnPropertyChanged(nameof(_selectedArea));
        }
    }
}

Solution:

The binding source of SelectedItem must have the same type as the type that is used in the ItemsSource, in your case that's Patio, while you're trying to use a string for it, which isn't possible.

Change this:

[ObservableProperty]
private ObservableCollection<Patio> _patio = new();

[ObservableProperty, NotifyPropertyChangedFor(nameof(CanPost))]
private string _selectedArea;

// Validations
public bool CanPost => !string.IsNullOrEmpty(EntryChassi)
    && !string.IsNullOrEmpty(Cracha)
    && !string.IsNullOrEmpty(SelectedArea);

To this:

[ObservableProperty]
private ObservableCollection<Patio> _patio = new();

[ObservableProperty, NotifyPropertyChangedFor(nameof(CanPost))]
private Patio _selectedArea;
     
// Validations
public bool CanPost => !string.IsNullOrEmpty(EntryChassi)
    && !string.IsNullOrEmpty(Cracha)
    && (SelectedArea is not null);
Answer

Login


Forgot Your Password?

Create Account


Lost your password? Please enter your email address. You will receive a link to create a new password.

Reset Password

Back to login