我在我的Xamarin.Forms应用程序中遇到了ObservableCollection问题。
我能够添加值(我可以在调试器中读取它们),但是视图不会更新。
到目前为止,我尝试了很多方法,但是似乎没有解决这个问题。
希望您能帮忙:)
这是我的代码:
private ObservableCollection<Transaction> transactions = new ObservableCollection<Transaction>();
public ObservableCollection<Transaction> Transactions
{
get { return transactions; }
set
{
transactions = value;
OnNotifyPropertyChanged();
}
}
public class Transaction:BaseViewModel
{
private string name = null;
private string price = null;
private double numPrice = 0;
private string date = null;
public string Name
{
get
{
return name;
}
set
{
OnNotifyPropertyChanged();
name = value;
}
}
public string Price
{
get
{
return price;
}
set
{
OnNotifyPropertyChanged();
price = value;
}
}
public double NumPrice
{
get
{
return numPrice;
}
set
{
OnNotifyPropertyChanged();
numPrice = value;
}
}
public string DateTime
{
get
{
return date;
}
set
{
OnNotifyPropertyChanged();
date = value;
}
}
}
我的BaseViewModel:
public class BaseViewModel : INotifyPropertyChanged
{
protected BaseViewModel()
{
}
#region Events
public event PropertyChangedEventHandler PropertyChanged;
#endregion
protected void OnNotifyPropertyChanged([CallerMemberName] string memberName = "")
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(memberName));
}
}
}
在XAML中:
<ScrollView>
<StackLayout BindableLayout.ItemsSource="{Binding Transactions}">
<BindableLayout.ItemTemplate>
<DataTemplate>
<Frame BackgroundColor="#4D4D4D" CornerRadius="10">
<StackLayout Orientation="Horizontal">
<StackLayout>
<Label Text="{Binding Name}"/>
<Label Text="{Binding DateTime}"/>
</StackLayout>
<Label Text="{Binding Price}" FontSize="20"
HorizontalOptions="EndAndExpand" VerticalOptions="CenterAndExpand" Margin="0,0,10,0" />
</StackLayout>
</Frame>
</DataTemplate>
</BindableLayout.ItemTemplate>
</StackLayout>
</ScrollView>
感谢您提前帮忙!
编辑: 这是我更新集合的方法:
public void AddTransaction(string name, double price, DateTime dateTime)
{
Transactions.Add(new Transaction()
{
Name = name,
Price = ($"-{price}€".Replace('.',',')),
NumPrice = price,
DateTime = dateTime.ToString("dd.MM.yyyy")
});
}
OnPropertyChanged
。它必须在设置值之后才能调用。 - Julian