WPF MVVM依赖项属性

use*_*121 1 wpf dependency-properties mvvm wpf-controls

我有以下情况:

  1. 我有一个用户控件,里面只有一个Grid.
  2. Grid的第一列是复选框列,它绑定到CustomerModel的IsSelected属性
  3. Grid的ItemsSource绑定到List <CustomerModel>
  4. 当用户检查任何CheckBox时,CustomerModel的相应IsSelected属性正在更新

查询:

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

  2. 此UserControl放在另一个窗口上

  3. 依赖属性"SelectedCustomerItems"绑定到WindowViewModel中的"SelectedCustomers"属性

但我没有通过此依赖项属性获取SelectedCustomer项.断点没有打到Get {}请建议....

小智 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  
Run Code Online (Sandbox Code Playgroud)

您必须了解DependencyProperty不仅仅是添加了一堆垃圾的属性,它是WPF绑定系统的一个钩子.这是一个庞大而复杂的系统,生活在海平面以下,你的DP漂亮地浮在水面上.它的行为方式是你不会期望的,除非你真正学到它.

您正在体验我们所有人对DP的第一次启示:绑定不通过属性访问器(即getset方法)访问DependencyProperty值.这些属性访问器是您只能从代码中使用的便捷方法.您可以省去它们并使用DependencyObject.GetValue和DependencyObject.SetValue,它们是系统的实际挂钩(请参阅上面示例中的getters/setter的实现).

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

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

有关DependencyProperties如何工作的更多信息,我强烈建议您阅读MSDN上的这篇精彩概述.