Reputation: 440
I have a button and want to update UI Label value on button click from ViewModel. I implemented INotifyPropertyChanged but it is not working. Property value doesn't update value to Label in UI in Xamarin Forms
MyViewModel
public class MyViewModel : INotifyPropertyChanged
{
public ICommand selectDurationCommand;
public ICommand SelectDurationCommand
{
get { return selectDurationCommand; }
set
{
selectDurationCommand = value;
OnPropertyChanged();
}
}
public string _fare{ get; set; }
public string Fare
{
get { return _fare; }
set
{
_fare = value;
OnPropertyChanged();
}
}
public event PropertyChangedEventHandler PropertyChanged;
public MyViewModel()
{
selectDurationCommand = new Command((object s) => get_fare(s));
_fare = "$00.00";
}
public void get_fare(object btn)
{
var b = (Button)btn;
_fare="$03.00";
}
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
FareDetails.xaml
<cl:BasePage xmlns="http://xamarin.com/schemas/2014/forms" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" x:Class="familyinfo.FareDetails" xmlns:cl="clr-namespace:familyinfo;assembly=familyinfo" x:Name="PDuration">
<Label FontSize="22" TextColor="Black" VerticalOptions="FillAndExpand" Font="Roboto-Medium" Text="{Binding Fare}" VerticalTextAlignment="Center" HorizontalTextAlignment="Center" />
<Button Command="{Binding Source={x:Reference PDuration}, Path=BindingContext.SelectDurationCommand}" CommandParameter="{x:Reference min15Button}" x:Name="min15Button" HeightRequest="30" HorizontalOptions="FillAndExpand" BorderRadius="8" Text="15 MIN" TextColor="#ffffff" BackgroundColor="#f2415c" />
</cl:BasePage>
FareDetails.xaml.cs
public partial class FareDetails : BasePage
{
MyViewModel _MyViewModel { get; set; }
public FareDetails()
{
InitializeComponent();
_MyViewModel = (MyViewModel)this.BindingContext;
}
}
Upvotes: 2
Views: 2591
Reputation: 905
Can you ensure that the value of the (MyViewModel)this.BindingContext is not null?
Replace the below code and check whether label value is showing or not
MyViewModel _MyViewModel { get; set; }
public FareDetails()
{
_MyViewModel = new MyViewModel();
BindingContext = _MyViewModel;
InitializeComponent();
}
Also set the public property (Fare = "$0.00") instead of private property (_fare = "$0.00")
Upvotes: 0
Reputation: 9346
For the PropertyChanged notification to be raised you need to set the value to the Property not to the private field.
Change your Command method to this:
public void get_fare(object btn)
{
var b = (Button)btn;
Fare="$03.00";
}
Note: your _fare
can safely be a private field.
private string _fare;
public string Fare
{
get { return _fare; }
set
{
_fare = value;
OnPropertyChanged();
}
}
Upvotes: 3