WPF MVVM依赖项属性

时间:2013-03-26 20:29:15

标签: wpf mvvm wpf-controls dependency-properties

我有以下情况:

  1. 我的用户控件内部只有一个网格。
  2. Grid的第一列作为复选框列,绑定到CustomerModel的IsSelected属性
  3. Grid的ItemsSource绑定到List< CustomerModel>
  4. 当用户检查任何CheckBox时,CustomerModel的相应IsSelected属性正在更新
  5. 查询:

    1. 我向UserControl添加了一个名为“SelectedCustomerItems”的依赖项属性,我希望它返回一个List< CustomerModel> (仅适用于IsSelected = true)

    2. 此UserControl位于另一个窗口

    3. 依赖属性“SelectedCustomerItems”绑定到WindowViewModel中的“SelectedCustomers”属性
    4. 但是我没有通过这个依赖属性获取SelectedCustomer项。断点没有点击Get {}请建议......

1 个答案:

答案 0 :(得分:6)

以这种方式实施您的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的第一次启示:绑定不通过属性访问器(即getset方法)访问DependencyProperty值。这些属性访问器是您可以从代码 中使用的便捷方法。您可以省去它们并使用DependencyObject.GetValue and DependencyObject.SetValue,它们是系统的实际挂钩(请参阅上面示例中的getter / setter的实现)。

如果您想收听更改通知,您应该在我的示例中执行上面所做的操作。您可以在注册DependencyProperty时添加更改通知侦听器。您还可以覆盖继承的DependencyProperties的“元数据”(我一直为DataContext执行此操作)以添加更改通知(有些人使用DependencyPropertyDescriptor为此,但我发现它们缺乏)。

但是,无论你做什么,都不要向DependencyProperties的getset方法添加代码!它们不会被绑定操作执行。

有关DependencyProperties如何工作的更多信息,请I highly suggest reading this great overview on MSDN.