下面您可以看到我的.xaml.cs代碼。該應用打開罰款。有4個用戶可以更改的文本框。當您在文本框中編輯默認值之一,然後單擊以不選中它時,該應用程序會崩潰並顯示System.StackOverflowException錯誤,並說我的get {}或Calc()函數有無限循環或遞歸,取決於哪個文本框被編輯。我希望應用程序在每次未編輯文本框時根據Calc()函數計算數字。我也想爲文本框定義一些起始值,但還沒有弄清楚如何去做。WPF4/C# - System.StackOverflowException崩潰應用程序
任何想法如何修復循環錯誤和初始值定義?
中的.xaml代碼的文本框遵循此模式:Text="{Binding DistanceBox}"
完整背後代碼如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.ComponentModel;
namespace ConverterApp
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
DataContext = new Variables();
}
}
public class Variables : INotifyPropertyChanged
{
// Declare the PropertyChanged event.
public event PropertyChangedEventHandler PropertyChanged;
private double m_distanceBox;
public double DistanceBox
{
get { return m_distanceBox; }
set
{
//If value hasn't changed, don't do anything
//if (m_distanceBox == value)
// return;
m_distanceBox = value;
// modify calc to read the text values
Calc();
// Call NotifyPropertyChanged when the source property
// is updated.
//if(PropertyChanged!= null)
NotifyPropertyChanged("DistanceBox");
}
}
private double m_widthBox;
public double WidthBox
{
get { return m_widthBox; }
set
{
m_widthBox = value;
// modify calc to read the text values
Calc();
// Call NotifyPropertyChanged when the source property
// is updated.
NotifyPropertyChanged("WidthBox");
}
}
private double m_lengthBox;
public double LengthBox
{
get { return m_lengthBox; }
set
{
m_lengthBox = value;
// modify calc to read the text values
Calc();
// Call NotifyPropertyChanged when the source property
// is updated.
NotifyPropertyChanged("LengthBox");
}
}
private double m_lensBox;
public double LensNeeded
{
get { return m_lensBox; }
set
{
m_lensBox = value;
// modify calc to read the text values
Calc();
// Call NotifyPropertyChanged when the source property
// is updated.
NotifyPropertyChanged("LensNeeded");
}
}
public void Calc()
{
double WidthBased = 2.95 * (DistanceBox/WidthBox);
double LengthBased = 3.98 * (DistanceBox/LengthBox);
if (WidthBased < LengthBased)
{
LensNeeded = Math.Round(WidthBased,2);
}else{
LensNeeded = Math.Round(LengthBased,2);
}
}
// NotifyPropertyChanged will raise the PropertyChanged event,
// passing the source property that is being updated.
public void NotifyPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this,
new PropertyChangedEventArgs(propertyName));
}
}
}
}
工作完美,謝謝! – 2011-06-13 20:48:41