本文介绍了Xamarin Forms 中的 UI 中的属性值不会更新到标签的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个按钮,想在 ViewModel 中单击按钮时更新 UI 标签值.我实现了 INotifyPropertyChanged 但它不起作用.Xamarin Forms 中的 UI 中的属性值不会将值更新为标签
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;
}
}
推荐答案
要引发 PropertyChanged 通知,您需要将值设置为 Property 而不是私有字段.
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";
}
注意:您的 _fare
可以安全地成为私有字段.
Note: your _fare
can safely be a private field.
private string _fare;
public string Fare
{
get { return _fare; }
set
{
_fare = value;
OnPropertyChanged();
}
}
这篇关于Xamarin Forms 中的 UI 中的属性值不会更新到标签的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!