何时使用WPF依赖属性与INotifyPropertyChanged

Kei*_*ill 35 wpf binding dependency-properties inotifypropertychanged

人们对INotifyPropertyChanged.PropertyChanged在视图模型中触发的简单.NET属性何时足够有任何指导?那么你什么时候想要升级到一个完整的依赖属性?或者DP主要用于观看?

Luk*_*don 53

有几种方法:

1.依赖属性

在使用依赖项属性时,它在具有可视外观的元素类中最有意义UIElement.

优点:

  • WPF为你做逻辑的东西
  • 像动画这样的机制只使用依赖属性
  • '适合'ViewModel风格

缺点:

  • 你需要派生形式 DependencyObject
  • 简单的东西有点尴尬

样品:

public static class StoryBoardHelper
{
    public static DependencyObject GetTarget(Timeline timeline)
    {
        if (timeline == null)
            throw new ArgumentNullException("timeline");

        return timeline.GetValue(TargetProperty) as DependencyObject;
    }

    public static void SetTarget(Timeline timeline, DependencyObject value)
    {
        if (timeline == null)
            throw new ArgumentNullException("timeline");

        timeline.SetValue(TargetProperty, value);
    }

    public static readonly DependencyProperty TargetProperty =
            DependencyProperty.RegisterAttached(
                    "Target",
                    typeof(DependencyObject),
                    typeof(Timeline),
                    new PropertyMetadata(null, OnTargetPropertyChanged));

    private static void OnTargetPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        Storyboard.SetTarget(d as Timeline, e.NewValue as DependencyObject);
    }
}
Run Code Online (Sandbox Code Playgroud)

2. System.ComponentModel.INotifyPropertyChanged

通常,在创建数据对象时,您将使用此方法.这是类似数据的东西的简单而简洁的解决方案.

优点和缺点 - 补充1.你需要只实现一个事件(PropertyChanged).

样品:

public class Student : INotifyPropertyChanged 
{ 
   public event PropertyChangedEventHandler PropertyChanged; 
   public void OnPropertyChanged(PropertyChangedEventArgs e) 
   { 
       if (PropertyChanged != null) 
          PropertyChanged(this, e); 
   } 
}

private string name; 
public string Name; 
{ 
    get { return name; } 
    set { 
           name = value; 
           OnPropertyChanged(new PropertyChangedEventArgs("Name")); 
        } 
} 
Run Code Online (Sandbox Code Playgroud)

3.PropertyName已更改

为具有指定名称的每个属性(fe NameChanged)上升事件.事件必须具有此名称,由您来处理/升级它们.类似的方法2.

4.获得绑定

使用FrameworkElement.GetBindingExpression()你可以获取BindingExpression对象并调用BindingExpression.UpdateTarget()刷新.

第一个和第二个最有可能取决于你的目标.

总而言之,它是Visual vs Data.


abh*_*hek 14

据我所知,DependencyProperty只在您需要时才需要

  1. PropertyValue继承
  2. 您需要允许在样式设置器中设置属性
  3. 使用动画作为属性

等等

普通属性不提供这些功能.