[英]WPF MVVM Dependency Properties
我有以下情況:
查詢:
我向UserControl添加了一個名為“ SelectedCustomerItems”的依賴項屬性,並希望它返回List <CustomerModel>(僅適用於IsSelected = true)
此UserControl放置在另一個窗口上
但是我沒有通過此依賴項屬性獲取SelectedCustomer項目。 斷點不在Get {}中。請建議...。
通過以下方式實現您的DP:
#region SomeProperty
/// <summary>
/// The <see cref="DependencyProperty"/> for <see cref="SomeProperty"/>.
/// </summary>
public static readonly DependencyProperty SomePropertyProperty =
DependencyProperty.Register(
SomePropertyPropertyName,
typeof(object),
typeof(SomeType),
// other types here may be appropriate for your situ
new FrameworkPropertyMetadata(null, OnSomePropertyPropertyChanged));
/// <summary>
/// Called when the value of <see cref="SomePropertyProperty"/> changes on a given instance of <see cref="SomeType"/>.
/// </summary>
/// <param name="d">The instance on which the property changed.</param>
/// <param name="e">The <see cref="System.Windows.DependencyPropertyChangedEventArgs"/> instance containing the event data.</param>
private static void OnSomePropertyPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
(d as SomeType).OnSomePropertyChanged(e.OldValue as object, e.NewValue as object);
}
/// <summary>
/// Called when <see cref="SomeProperty"/> changes.
/// </summary>
/// <param name="oldValue">The old value</param>
/// <param name="newValue">The new value</param>
private void OnSomePropertyChanged(object oldValue, object newValue)
{
}
/// <summary>
/// The name of the <see cref="SomeProperty"/> <see cref="DependencyProperty"/>.
/// </summary>
public const string SomePropertyPropertyName = "SomeProperty";
/// <summary>
///
/// </summary>
public object SomeProperty
{
get { return (object)GetValue(SomePropertyProperty); }
set { SetValue(SomePropertyProperty, value); }
}
#endregion
您必須了解DependencyProperty不僅僅是添加了一大堆垃圾的屬性,它還是WPF綁定系統的一個鈎子。 這是一個龐大而復雜的系統,其生活在DP精心漂浮的海平面以下。 除非您真正學習它,否則它的行為方式是您不會期望的。
您正在經歷我們所有人對DP的第一個啟示:綁定不會通過屬性訪問器(即get
和set
方法)訪問DependencyProperty值。 這些屬性訪問器是供你只代碼中使用的簡便方法。 您可以省去它們,而使用DependencyObject.GetValue和DependencyObject.SetValue ,它們是連接到系統的實際掛鈎(請參見上面示例中的getter / setter的實現)。
如果您想聽更改通知,則應該執行我在示例中所做的操作。 您可以在注冊DependencyProperty時添加一個更改通知偵聽器。 您還可以覆蓋繼承的DependencyProperties的“元數據”(我一直在DataContext
這樣做),以便添加更改通知(為此,有些人使用DependencyPropertyDescriptor
,但我發現它們缺少)。
但是,無論您做什么,都不要將代碼添加到DependencyProperties的get
和set
方法中! 它們不會通過綁定操作執行。
有關DependencyProperties的工作方式的更多信息, 我強烈建議閱讀有關MSDN的出色概述。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.