WPF依赖属性和InotifyChanged属性

时间:2015-08-02 08:58:46

标签: wpf

在真实场景中使用/创建依赖属性的真正用途是什么?

如果我们使用通知目的,那么我将选择InotifyChanged Property。

我从未在实时项目中看到/使用过依赖属性的真实用途吗?

有人可以告诉我实时Scenrios需要DP吗?

2 个答案:

答案 0 :(得分:2)

如果您创建的自定义控件包含您希望可绑定的属性(例如,代码如下),则无法使用INotifyPropertyChanged,您必须使用DependencyProperty

假设你有UserControl这样:

public partial class MyUserControl : UserControl
{
    public List<ItemViewModel> ItemsSource
    {
        get { return (List<ItemViewModel>)GetValue(ItemsSourceProperty); }
        set { SetValue(ItemsSourceProperty, value); }
    }

    // Using a DependencyProperty as the backing store for ItemsSource.  This enables animation, styling, binding, etc...
    public static readonly DependencyProperty ItemsSourceProperty =
        DependencyProperty.Register("ItemsSource", typeof(List<ItemViewModel>), typeof(MyUserControl ), new PropertyMetadata(null));
}

然后您可以通过这种方式在主窗口中设置ItemsSource DependencyProperty )的绑定:

<uc:MyUserControl ItemsSource="{Binding MyItems}"  />

摘要:

通常,绑定看起来像这样:T = "{Binding S}"

  • T是绑定的目标
  • S是绑定的来源

  • T只允许为 DependencyProperty 。例如:

    MyDependencyProperty =&#34; {Binding something}&#34;

  • S通常是 INPC-Property 。 e.g:

    某事=&#34; {绑定MyINPCProperty}&#34;

答案 1 :(得分:1)

来自MSDN

  

依赖属性的目的是提供一种计算方法   基于其他输入值的属性值。这些   其他输入可能包括系统属性,如主题和用户   偏好,及时财产确定机制,如   数据绑定和动画/故事板,多用途模板等   作为资源和样式,或通过父子知道的值   与元素树中其他元素的关系。另外,一个   可以实现依赖属性以提供自包含   验证,默认值,监视对其他更改的回调   属性,以及可以强制基于属性值的系统   潜在的运行时信息派生类也可以改变一些   通过覆盖现有财产的具体特征   依赖属性元数据,而不是覆盖实际   实现现有属性或创建新属性。

相关问题