嗨,我有一个TextBlock,它的Text属性绑定到一个ViewModel属性(总票价),我想创建一个按钮来帮助我将数据和textBlock都重置为0。
我尝试将Total设置为0,但是遇到StackOverflowException。
我正在学习WPF,所以如果是新手,请回答我的问题!
TicketViewModel
public ObservableCollection<TicketModel> TicketsEnVente { get; set; }
public TicketViewModel()
{
TicketsEnVente = new ObservableCollection<TicketModel>();
TicketsEnVente.CollectionChanged += CollectionChanged;
}
private void CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
OnPropertyChanged("Total");
}
public float Total
{
get { return TicketsEnVente.Sum(x =>x.Prix); }
set
{
Total = value;
OnPropertyChanged("Total");
}
}
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged(string propertyName)
{
var handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
Xaml
<TextBlock x:Name="Total" Text="{Binding Total}"/>
答案 0 :(得分:2)
您将收到StackOverflowException,因为您无限调用Total属性的setter。引入私有字段来避免该问题。您的逻辑很好,现在将Total设置为0应该会刷新绑定视图。
private float total;
public float Total
{
get { return TicketsEnVente.Sum(x =>x.Prix); }
set
{
total = value;
OnPropertyChanged("Total");
}
}
请注意,您可能希望按钮清除数据收集,然后触发OnPropertyChanged(Total)。
public void ResetData()
{
TicketsEnVente.Clear();
OnPropertyChanged("Total");
}