我要去嘗試來概括你:
依賴屬性:
public int MyProperty
{
get { return (int)GetValue(MyPropertyProperty); }
set { SetValue(MyPropertyProperty, value); }
}
// Using a DependencyProperty as the backing store for MyProperty. This enables animation, styling, binding, etc...
public static readonly DependencyProperty MyPropertyProperty =
DependencyProperty.Register("MyProperty", typeof(int), typeof(MyClass), new UIPropertyMetadata(MyDefaultValue));
這是完整的語法,您不必記住它,只需在Visual Studio中使用「propdp」片段即可。
「get」必須返回它引用的類型的值(在我的示例中爲int)。無論何時您致電
int MyVar = MyProperty;
評估「get」內部的代碼。
集合有類似的機制,只有你有另外一個關鍵字:「價值」,這將是分配給MyVariable的值:
MyProperty = 1;
將調用myProperty的「集」和「價值」會「 1" 。
現在的RoutedEvents:
在C#(如C++,糾正我,如果我錯了),訂閱一個事件,你做
MyProperty.MyEvent += MyEventHandler;
,將調用「添加「 - >你正在給堆棧添加一個處理程序。 現在,因爲它是不會自動垃圾收集,我們要避免內存泄漏,我們這樣做:
MyProperty.MyEvent -= MyEventHandler;
使我們的對象可以被安全地處理時,我們不需要它了。 即時評估「刪除」表達式。
這些機制允許你做多件事情一個單一的「得到」,在WPF中廣泛使用的例子是:
private int m_MyProperty;
public int MyProperty
{
get
{
return m_MyProperty;
}
set
{
if(m_MyProperty != value)
{
m_MyProperty = value;
RaisePropertyChanged("MyProperty");
}
}
}
其中,在實現INotifyPropertyChanged一個視圖模型,將在通知綁定您的查看該屬性已更改並需要重新檢索(因此他們將調用「get」)
這是C#語言的基礎知識,我相信您必須通過有關.NET屬性和事件的MSDN讀取 – sll
同意@sil,這不是(直接)與WPF相關的。在查看Routed/Dependency變體之前,您應該瞭解'正常'屬性和事件。 –