Saturday, January 29, 2011

Dependency property in WPF

Here is sample application for dependency properties. Here is a person class whose property triggers a notification when the values are changed

person.cs class


public class Person :DependencyObject
    {
        public static readonly DependencyProperty LastNameProperty = DependencyProperty.Register
            ("LastName", typeof(string), typeof(Person));
        public static readonly DependencyProperty FirstNameProperty = DependencyProperty.Register
            ("FirstName", typeof(string), typeof(Person));


        public string LastName
        {
            get
            {
                return (string)GetValue(LastNameProperty);
            }
            set
            {
                SetValue(LastNameProperty, value);
            }
        }
        public string FirstName
        {
            get
            {
                return (string)GetValue(FirstNameProperty);
            }
            set
            {
                SetValue(FirstNameProperty, value);
            }
                
        }
      
        public string Name
        {
            get { return this.LastName + "," + this.FirstName; }
        }
    }

Here is the XAML file



    
        
    
    
        
            

            

            
        
    



 public partial class Window1 : Window
    {
        public Window1()
        {
            InitializeComponent();
            BindData();
        }
        private void BindData()
        {
         base.DataContext = new Person { FirstName = "puru", LastName = "adhikari" };
        }
    }
Hope this helps :)