Search code examples
xamlxamarinmvvmxamarin.formsprism

Binding default values on Picker and DatePicker when ViewModel loading


I want to set selected date on DatePicker and Selected item on Picker when on when ViewModel class loading. How I am doing it

public override void OnNavigatedTo(INavigationParameters parameters)
{
    base.OnNavigatedTo(parameters);
    var objL = parameters.GetValue<LeaveManagement>("LeaveItem");
    SelectedFromDate = objL.StartDate;
    SelectedToDate = objL.EndDate;
    SelectedLeaveType = new SpinnerBind { Name = objL.LeaveTypeCD, Value = objL.LeaveTypeId };           
}

private DateTime? _selectedFromDate;
public DateTime? SelectedFromDate
{
    get { return _selectedFromDate; }
    set { _selectedFromDate = value; }
}
private DateTime? _selectedToDate;
public DateTime? SelectedToDate
{
    get { return _selectedToDate; }
    set { _selectedToDate = value; }
}

private ObservableCollection<SpinnerBind> _leaveType;
public ObservableCollection<SpinnerBind> LeaveType
{
    get { return _leaveType; }
    set
    {
        SetProperty(ref _leaveType, value);
    }
}
private SpinnerBind _selectedLeaveType;
public SpinnerBind SelectedLeaveType
{
    get { return _selectedLeaveType; }
    set
    {
        SetProperty(ref _selectedLeaveType, value);
    }
}

This is my XAMl

<RelativeLayout>
    <DatePicker Format="dd/MM/yyyy"   Date="{Binding SelectedFromDate}"/>

    <DatePicker  Format="dd/MM/yyyy" Date="{Binding SelectedToDate}"/>

    <Picker SelectedItem="{Binding SelectedLeaveType, Mode=TwoWay}" ItemsSource="{Binding LeaveType,Mode=TwoWay}"
            TitleColor="Black" TextColor="Black" Title="--Select--"/>
</RelativeLayout>

But all values Startdate, Enddate and SelectedLeaveType not getting set. However Picker is binding with LeaveType How can I solve this issue?


Solution

  • When a property of a view model changes, it needs to raise INotifyPropertyChanged.PropertyChanged to update the bindings.

    Prism provides the BindableBase base class for view models, which has a SetProperty method normally used to update the backing field and raise the event if needed.

    That is, you want something like this

    public DateTime? SelectedFromDate
    {
        get { return _selectedFromDate; }
        set { SetProperty( ref _selectedFromDate, value ); }
    }
    

    Edit: To bind Picker with default selected item, initialize SelectedLeaveType from the Source.