Posted by: Zeeshan Amjad | September 26, 2009

Read only Attached Property


Making read only attached property is very much similar to making read only dependency property. It means first we have to create an object of DependencyPropertyKey class and then call the RegisterAttachedReadonly function of Dependency property class. Here is a simple program to demonstrate these steps.

  1: using System;
  2: using System.Windows;
  3: 
  4: public class Employee : DependencyObject
  5: {
  6:     public static readonly DependencyProperty NameProperty =
  7:         DependencyProperty.Register("Name", typeof(string), typeof(Employee));
  8: 
  9:     public static readonly DependencyPropertyKey CompanyPropertyKey =
 10:         DependencyProperty.RegisterAttachedReadOnly("Company", typeof(string), typeof(Employee),
 11:         new PropertyMetadata("WPF In Corp"));
 12: 
 13:     public static readonly DependencyProperty CompanyProperty =
 14:         CompanyPropertyKey.DependencyProperty;
 15: 
 16:     public string Name
 17:     {
 18:         get { return (string)GetValue(NameProperty); }
 19:         set { SetValue(NameProperty, value); }
 20:     }
 21: 
 22:     public static string GetCompany(UIElement element)
 23:     {
 24:         return (string)element.GetValue(CompanyProperty);
 25:     }
 26: }
 27: 
 28: public class MyWindow : Window
 29: {
 30:     public MyWindow()
 31:     {
 32:         Title = "Read only Attached Property";
 33:         Width = 400;
 34:         Height = 300;
 35:     }
 36: }
 37: 
 38: public class AttachedProperty
 39: {
 40:     [STAThread]
 41:     public static void Main()
 42:     {
 43:         MyWindow win = new MyWindow();
 44: 
 45:         Employee emp = new Employee();
 46:         emp.Name = "Bob Smith";
 47: 
 48:         String text = String.Format("Name = {0}\nCompany = {1}",
 49:             emp.Name, emp.GetValue(Employee.CompanyProperty));
 50: 
 51:         win.Content = text;
 52: 
 53:         Application app = new Application();
 54:         app.Run(win);
 55:     }
 56: }
 57: 

Here is the output of this program.

ReadonlyAttachedProperty

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Categories

%d bloggers like this: