如何在Xamarin.Forms中实现INotifyPropertyChanged [英] How to implement INotifyPropertyChanged in Xamarin.Forms
问题描述
我正在Xamarin.Forms中实现购物车.在我的购物车页面上,有一个ListView
及其数据.每个单元格都包含一个按钮,用于选择 item 和 amount 的计数.在购物车视图中,有一个总计标签.
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.
我的问题是,数字选择器更改时,总计没有更新.在项目添加视图单元格时调用该计算方法.我知道我需要为此实现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实施为Dictionary结构,例如:
public abstract class ViewModelBase : ObservableProperty
{
public Dictionary<string,ICommand> Commands { get; protected set; }
public ViewModelBase()
{
Commands = new Dictionary<string,ICommand>();
}
}
因此,ViewModel中的所有待办事项都只是继承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屋!