Home > front end >  values in the view model not updating back to the UI in MAUI
values in the view model not updating back to the UI in MAUI

Time:01-03

I'm trying to get two dates from the date picker and calculate no of days between those as an integer and update it back into a label in xaml file,

I'm using community toolkit to generate the code in view model. But the issue is the difference of the dates not updating back into the UI.

xaml file

<DatePicker

x:Name="fromdate"

Date="{Binding Date1}"

FontAttributes="Bold" FontSize="Medium"

Grid.Column="0"

Grid.Row="1" />





<DatePicker

x:Name="todate"

Date="{Binding Date2}"

FontAttributes="Bold" FontSize="Medium"

Grid.Row="1"

Grid.Column="1"/>

<Label Text="{Binding Nodays,Mode=TwoWay}" FontSize="Medium"/>



View Model





public partial class AddLeaveViewModel : ObservableObject

{

[ObservableProperty]

DateTime date1 = DateTime.Today;



[ObservableProperty]

DateTime date2 = DateTime.Today;



[ObservableProperty]

int nodays;



[RelayCommand]

public async void SubmitClicked()

{

try

{

TimeSpan difference = Date2 - Date1;

nodays = difference.Days;

}catch(Exception e){

Console.WriteLine(e);

}



}



}

I'm expecting to get the difference of the date back to the UI in real time using communitytoolkit

CodePudding user response:

Read this: https://learn.microsoft.com/en-us/dotnet/csharp/fundamentals/coding-style/coding-conventions

Property A has field _a, not a.

Edit: To clarify this a bit, when you annotate your nodays field, in the auto generated code you have property Nodays.

The setter of the Nodays property uses magic code to make your binding work. Setting the field directly has no such effect.

The correct way of writing that field will be _nodays. Then use the auto generated property Nodays.

CodePudding user response:

You can try to replace code :

 nodays = difference.Days;

with:

 Nodays = difference.Days;

So, the code of SubmitClicked will be as follows:

[RelayCommand]   
public async void SubmitClicked()    
{    
   try    
   {   
      TimeSpan difference = Date2 - Date1;  

      //nodays = difference.Days;
       Nodays = difference.Days;

     }catch(Exception e){

     Console.WriteLine(e);
}
  • Related