如何在 Xamarin.Forms 中实现 INotifyPropertyChanged [英] How to implement INotifyPropertyChanged in Xamarin.Forms
问题描述
我正在 Xamarin.Forms 中实现购物车.在我的购物车页面中有一个带有数据的 ListView
.每个单元格都包含一个按钮,用于选择项目 的数量和数量.在购物车视图中有一个总计标签.
I am implementing a cart in Xamarin.Forms. In my cart page there is a ListView
with data. Each of the cell contains a button to select the count of item and amount. In the cart view there is a grand total label.
我的问题是当数字选择器发生变化时,总数没有更新.计算方法在 item 添加视图单元格时调用.我知道我需要为此实现 INotifyProperty
,但我不确定如何去做.
My problem is the grand total is not updating while the number picker changes. The calculation method is called upon item adding view cell. I know that i need to implement INotifyProperty
for this, but I'm unsure of how to do it.
我有一个基础视图模型,它继承了包含一个事件的 INotifyProperty
.
I have a base view model which inherits INotifyProperty
that contains an event.
public class BaseViewModel : INotifyPropertyChanged
{
private double _price;
public double Price
{
get
{
return _price;
}
set
{
_price = value;
OnPropertyChanged("Price");}
}
protected virtual void OnPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
查看模型
public BaseViewModel()
{
App.Instance.ViewModel = this;
TempList = TempList ?? new ObservableCollection<cm_items>();
this.Title = AppResources.AppResource.Cart_menu_title;
this.Price = CartCell.price;
}
推荐答案
作为一种设计方法,最好将 MVVM 实现为子类并将其实现到您的 ViewModel
.
As a design methodology, its better to implement MVVM as a subclass and implement it to your ViewModel
.
示例实现:
public class ObservableProperty : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged(string propertyName)
{
var handler = PropertyChanged;
if (handler != null)
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
我还强烈建议将 ICommand 实现为字典结构,例如:
public abstract class ViewModelBase : ObservableProperty
{
public Dictionary<string,ICommand> Commands { get; protected set; }
public ViewModelBase()
{
Commands = new Dictionary<string,ICommand>();
}
}
所以你的 ViewModel 中的所有 todo 只是继承 ViewModelBase 类并使用它
class LoginViewModel : ViewModelBase
{
#region fields
string userName;
string password;
#endregion
#region properties
public string UserName
{
get {return userName;}
set
{
userName = value;
OnPropertyChanged("UserName");
}
}
public string Password
{
get{return password;}
set
{
password = value;
OnPropertyChanged("Password");
}
}
#endregion
#region ctor
public LoginViewModel()
{
//Add Commands
Commands.Add("Login", new Command(CmdLogin));
}
#endregion
#region UI methods
private void CmdLogin()
{
// do your login jobs here
}
#endregion
}
最后:Xaml 用法:
<Entry Placeholder="Username" Text="{Binding UserName}"/>
<Entry Placeholder="Password" Text="{Binding Password}" IsPassword="True"/>
<Button Text="Login" Command="{Binding Commands[Login]}"/>
这篇关于如何在 Xamarin.Forms 中实现 INotifyPropertyChanged的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!