2012-05-09 43 views
6

我正在学习依赖属性。我读了很多帖子&书,但我仍然不清楚。依赖属性错误

下面显示的程序是我写的学习内容。有些错误,请帮助解决。我有问题。

  1. 主要使用习惯依赖属性元素是变化的通知?
  2. 我在WPF课本中找到了按钮的'IsDefaultProperty'代码。这意味着'IsDefault'属性是一个依赖属性?
  3. 他们为什么显示该代码?这意味着,在内部,在Button类中,它的定义是这样的吗? (他们展示了内部代码?)或者他们展示了如何定义为自定义?

这里是我的代码:

namespace DependencyProperties 
{ 
    public class Contact 
    { 
     private int id=100; 
     private string name="shri"; 
     public static readonly DependencyProperty IsPresentProperty; 

     public int ID 
     { 
      get { return id; } 
     } 
     public string NAME 
     { 
      get { return name; } 
     } 

     static Contact() 
     { 
      IsPresentProperty = DependencyProperty.Register("IsPresent", typeof(bool),typeof(Contact),new FrameworkPropertyMetadata(false,new PropertyChangedCallback(OnIsPresentChanged))); 
     } 

     public bool Present 
     { 
      get { return (bool)GetValue(Contact.IsPresentProperty); } 
      set { SetValue(Contact.IsPresentProperty, value); } 
     } 

     private static void OnIsPresentChanged(DependencyObject o, DependencyPropertyChangedEventArgs e) 
     { 

     } 
    } 
} 

而且我看到的错误:

> Error: GetValue and SetValue does not exist in the current context 

回答

14

The main use of custom Dependency property element is for the notification of change?

没有,那还可以安排由具有类实现INotifyPropertyChanged为好。依赖属性提供更改通知,但真正的基本原理是不同的。见Why dependency properties?How is the WPF property system economical?

I found an 'IsDefaultProperty' code for Button in a WPF text book. It means 'IsDefault' property is a dependency property?

是。命名字段“FooBarProperty”是用于定义依赖项属性的WPF约定;你可以检查IsDefaultProperty的文档以查看它确实是一个依赖属性,甚至IsDefault文档都有一个名为“依赖属性信息”的部分。

Why they shown that code? It means, internally, in Button class, its defined like that? (They showed internal code?) or they showed how to define as custom?

我不知道是什么‘即’代码,但肯定的,属性是几乎可以肯定一样,在Button定义(‘几乎’是因为我不敢肯定你是指什么)。

Error: GetValue and SetValue does not exist in the current context

这是因为你不是从DependencyObject派生。

12

DependencyProperty实例必须在DependencyObject的实例上定义。所以,你的班级必须来自DependencyObject,或其中一个子类。 WPF中的许多类型都源自此,包括Button

所以让你的代码在这种情况下工作,你必须使用:

public class Contact : DependencyObject 
{ 
    // ... 

这就是为什么你在GetValueSetValue收到错误 - 他们是在DependencyObject定义。

+0

谢谢分配。错误已解决。 – SHRI

+0

非常有帮助。这个答案应该有更多的投票。 –