在.NET中,我有一個名爲Caption的類。我有另一個叫Gauge的課。在Gauge類中,我有一個定義爲Caption的屬性。觸發另一個類中的事件
我想弄清楚如何做到以下幾點: 當我的Caption類中的某個屬性發生變化時,我該如何獲取它以執行Gauge類中的子例程?我想我必須聲明一個事件和AddHandlers來解僱它,但我想不出如何實現這一點。
在.NET中,我有一個名爲Caption的類。我有另一個叫Gauge的課。在Gauge類中,我有一個定義爲Caption的屬性。觸發另一個類中的事件
我想弄清楚如何做到以下幾點: 當我的Caption類中的某個屬性發生變化時,我該如何獲取它以執行Gauge類中的子例程?我想我必須聲明一個事件和AddHandlers來解僱它,但我想不出如何實現這一點。
你會想看看在實現INotifyPropertyChanged界面,而這正是爲此目的設計的 - 引發事件時的屬性類實例更改。
在this MSDN page上給出了一個很好的使用例子。
// This class implements a simple customer type
// that implements the IPropertyChange interface.
public class DemoCustomer : INotifyPropertyChanged
{
// These fields hold the values for the public properties.
private Guid idValue = Guid.NewGuid();
private string customerName = String.Empty;
private string companyNameValue = String.Empty;
private string phoneNumberValue = String.Empty;
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged(String info)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(info));
}
}
// The constructor is private to enforce the factory pattern.
private DemoCustomer()
{
customerName = "no data";
companyNameValue = "no data";
phoneNumberValue = "no data";
}
// This is the public factory method.
public static DemoCustomer CreateNewCustomer()
{
return new DemoCustomer();
}
// This property represents an ID, suitable
// for use as a primary key in a database.
public Guid ID
{
get
{
return this.idValue;
}
}
public string CompanyName
{
get {return this.companyNameValue;}
set
{
if (value != this.companyNameValue)
{
this.companyNameValue = value;
NotifyPropertyChanged("CompanyName");
}
}
}
public string PhoneNumber
{
get { return this.phoneNumberValue; }
set
{
if (value != this.phoneNumberValue)
{
this.phoneNumberValue = value;
NotifyPropertyChanged("PhoneNumber");
}
}
}
}
public class Caption
{
private int myInt;
public event EventHandler MyIntChanged;
private void OnMyIntChanged()
{
var handler = this.MyIntChanged;
if (handler != null)
{
handler(this, EventArgs.Empty);
}
}
public int MyInt
{
get
{
return this.myInt;
}
set
{
if (this.myInt != value)
{
this.myInt = value;
this.OnMyIntChanged();
}
}
}
}
現在
所以,在你有瓜葛類:
public class Guage
{
private Caption caption;
public Caption Caption
{
get
{
return this.caption;
}
set
{
if (this.caption!= value)
{
this.caption= value;
this.caption.MyIntChanged += new EventHandler(caption_MyIntChanged);
}
}
}
private void caption_MyIntChanged(object sender, EventArgs e)
{
//do what you gotta do
}
}
其他方式 - 他希望Gauge類成爲事件偵聽器和Caption類來將其關閉。 – technophile 2009-06-05 20:31:25
好吧,我想!這次我明白了。該死的,今天踢我的屁股......這是你想要的嗎? – BFree 2009-06-05 20:37:13