Dependency Property

ramesh raja 21 Reputation points
2021-02-18T07:54:41.28+00:00

how to use Dependency Property in WPF ? How to use it in MVVM ? a sudo code is much more helpfull than theory ?
I have read lot of articals but non is given best explanation.

XAML
XAML
A language based on Extensible Markup Language (XML) that enables developers to specify a hierarchy of objects with a set of properties and logic.
775 questions
0 comments No comments
{count} votes

2 answers

Sort by: Most helpful
  1. DaisyTian-1203 11,616 Reputation points
    2021-02-19T02:24:59.8+00:00

    DependencyProperty represents a property that can be set through methods such as, styling, data binding , animation , and inheritance.
    TextBox's Text property is a DependencyProperty, and I will show my sample of binding data to it with MVVM. You need to read the Basic data binding concepts to know how the data is bound before starting.

    Model Part:

     public class PersonModel : INotifyPropertyChanged  
        {  
            public event PropertyChangedEventHandler PropertyChanged;  
      
            protected void OnPropertyChange(string propertyName)  
            {  
                if (PropertyChanged != null)  
                {  
                    PropertyChanged(this, new PropertyChangedEventArgs(propertyName));  
                }  
            }  
      
            private string name;  
            public string Name  
            {  
                get { return name; }  
                set  
                {  
                    name = value;  
                    OnPropertyChange("Name");  
                }  
            }  
            private int age;  
            public int Age  
            {  
                get { return age; }  
                set  
                {  
                    age = value;  
                    OnPropertyChange("Age");  
                }  
            }  
        }  
    

    View Part:

     <Window.DataContext>  
            <local:PersonViewModel></local:PersonViewModel>  
        </Window.DataContext>  
        <Grid >  
            <Grid.RowDefinitions>  
                <RowDefinition Height="50"></RowDefinition>  
                <RowDefinition Height="50"></RowDefinition>  
            </Grid.RowDefinitions>  
            <Grid.ColumnDefinitions>  
                <ColumnDefinition Width="*"></ColumnDefinition>  
                <ColumnDefinition Width="4*"></ColumnDefinition>  
            </Grid.ColumnDefinitions>  
            <Label Grid.Column="0" Grid.Row="0" Content="Name:"/>  
            <TextBox Grid.Column="1" Grid.Row="0" Text="{Binding User.Name,Mode=TwoWay}" Width="200" HorizontalAlignment="Left" Height="30" />  
            <Label Grid.Column="0" Grid.Row="1"  Content="Num:" />  
            <TextBox Name="txtNum" Grid.Column="1" Grid.Row="1"  Text="{Binding User.Age,Mode=TwoWay}" HorizontalAlignment="Left" Height="30" Width="200"/>  
        </Grid>  
    

    ViewModel Part:

    class PersonViewModel  
        {  
            private PersonModel user;  
            public PersonModel User  
            {  
                get { return user; }  
                set  
                {  
                    user = value;  
                }  
            }  
            public PersonViewModel()  
            {  
                User = new PersonModel { Name = "John", Age = 11 };  
            }  
        }  
    

    If the response is helpful, please click "Accept Answer" and upvote it.
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments

  2. Peter Fleischer (former MVP) 19,306 Reputation points
    2021-02-19T05:47:38.867+00:00

    Hi,
    try following demo. Demo include UserControl with simple property, DependencyProperty and include DependencyObject with attached property.

    XAML MainWindow:

    <Window x:Class="WpfApp1.Window032"  
            xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"  
            xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"  
            xmlns:d="http://schemas.microsoft.com/expression/blend/2008"  
            xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"  
            xmlns:local="clr-namespace:WpfApp032"  
            mc:Ignorable="d"  
            Title="MainWindow" Height="450" Width="800">  
      <Window.DataContext>  
        <local:ViewModel/>  
      </Window.DataContext>  
      <StackPanel>  
        <TextBox Text="{Binding Prop1, UpdateSourceTrigger=PropertyChanged}"/>  
        <!--<local:UC SimpleProp="{Binding Prop1}"/> Binding to SimpleProp is impossible-->  
        <local:UC Height="100"   
                  SimpleProp="simple string"  
                  DepProp="{Binding Prop1}"  
                  local:DepObject.AttProp="True"/>  
      </StackPanel>  
    </Window>  
    

    And classes:

    using System.ComponentModel;  
    using System.Runtime.CompilerServices;  
    using System.Windows;  
    using System.Windows.Controls;  
    using System.Windows.Media;  
      
    namespace WpfApp032  
    {  
      public class ViewModel : INotifyPropertyChanged  
      {  
        // simple property in ViewModel  
        private string _prop1 = "start string";  
        public string Prop1  
        {  
          get => this._prop1;  
          set { this._prop1 = value; OnPropertyChanged(); } // Notify changes to refresh UI  
        }  
      
        // implements INotifyPropertyChanged  
        public event PropertyChangedEventHandler PropertyChanged;  
        private void OnPropertyChanged([CallerMemberName] string propName = "") =>  
          PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propName));  
      }  
      
      /// <summary>  
      /// UserControl  
      /// </summary>  
      public class UC : UserControl  
      {  
        // ctor  
        public UC() => this.Loaded += UC_Loaded;  
      
        // controls for design  
        private Border bo = new Border() { BorderBrush = Brushes.Red, BorderThickness = new Thickness(3) };  
        private StackPanel stp = new StackPanel();  
        private Label lbl1 = new Label();  
        private Label lbl2 = new Label();  
      
        // load design  
        private void UC_Loaded(object sender, RoutedEventArgs e)  
        {  
          this.Content = bo;  
          bo.Child = stp;  
          lbl1.Content = SimpleProp;  
          stp.Children.Add(lbl1);  
          stp.Children.Add(lbl2);  
        }  
      
        /// <summary>  
        /// simple property  
        /// </summary>  
        public string SimpleProp { get; set; }  
      
        /// <summary>  
        /// DependencyProperty  
        /// </summary>  
        public static DependencyProperty DepPropProperty =  
          DependencyProperty.Register("DepProp", typeof(string), typeof(UC),  
            new PropertyMetadata("start", OnDepPropChanged));  
        private static void OnDepPropChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)  
        {  
          var uc = d as UC;  
          uc.lbl2.Content = e.NewValue;  
        }  
        public string DepProp { get; set; }  
      }  
      
      /// <summary>  
      /// DependencyObject with attached property  
      /// </summary>  
      public class DepObject : DependencyObject  
      {  
        /// <summary>  
        /// Attached property  
        /// </summary>  
        public static DependencyProperty AttPropProperty =  
          DependencyProperty.RegisterAttached("AttProp", typeof(bool), typeof(UC),  
            new PropertyMetadata(false, OnAttPropChanged));  
        public static bool GetAttProp(DependencyObject obj) =>   
          (bool)obj.GetValue(AttPropProperty);  
        public static void SetAttProp(DependencyObject obj, bool value) =>  
          obj.SetValue(AttPropProperty, value);  
        private static void OnAttPropChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)  
        {  
          var uc = d as UC;  
          if (uc == null || !(e.NewValue is bool) || !(bool)(e.NewValue)) return;  
          uc.MouseEnter += (sender, ev) => uc.Background = Brushes.Lime;  
          uc.MouseLeave += (sender, ev) => uc.Background = Brushes.White;  
        }  
      }  
    }  
    

    Result:

    69876-x.gif

    0 comments No comments