Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dependency Property In WPF/SilverLight

I have searched on google about how to get started with the dependency property used in WPF/silverlight but didn't get any idea of the dependency property, can any one tell me about it , from beginner point of view, so that I get some idea about it and use it in my project

thanks in advance.

Can any one give me link or code example of simple application which explain in simple manner what is dependency Property is ??? I will be very thankfull


1 Answers

I find that implementing a DependencyProperty often involves four parts:

  • The DependencyProperty itself
  • Property with get and set
  • Static changed handler
  • Instance change handler

You can add a dependency property to a UserControl so that you can data bind to something in the DataContext where the UserControl is instantiated. For example you could add a property to a SoUserControl:

    #region SampleProperty // Demo for SO 2424526

    public static readonly DependencyProperty SamplePropertyProperty
        = DependencyProperty.Register("SampleProperty", typeof(int), typeof(SoUserControl), new PropertyMetadata(OnSamplePropertyChanged));


    /// <summary>
    /// Demo for SO 2424526
    /// Gets or sets dependency property.
    /// </summary>
    public int SampleProperty
    {
        get { return (int)GetValue(SamplePropertyProperty); }
        set { SetValue(SamplePropertyProperty, value); }
    }

    /// <summary>
    /// Handld changes to SamplePropertyProperty by calling a handler in the associated object.
    /// </summary>
    /// <param name="obj">object the property is associated with</param>
    /// <param name="e">details of change</param>
    static void OnSamplePropertyChanged(DependencyObject obj, DependencyPropertyChangedEventArgs e)
    {
        (obj as SoUserControl).OnSamplePropertyChanged(e);
    }

    /// <summary>
    /// Handle changes to the SamplePropertyProperty dependency property.
    /// </summary>
    /// <param name="e">details of change</param>
    private void OnSamplePropertyChanged(DependencyPropertyChangedEventArgs e)
    {
        int SamplePropertyNewValue = (int)e.NewValue;
        // do something with the internal logic of the control
    }

    #endregion
like image 167
Doug Ferguson Avatar answered Jan 22 '26 04:01

Doug Ferguson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!