Lester's WPF\SL Blog

Simple, Easy & Beautiful

Listening to DependencyProperty changes

Listening to DependencyProperty changes

Rate This
  • Comments 8

Dependency property is a pretty kewl concept.  You got to agree on that J.  One the nice features is the ability to listen to the changes in these properties and I tend to use it a lot. The SDK way would be to derive from the control, override the dependencyproperty metadata and specify the propertychangedCallback in the signature. Hmmm… pretty cumbersome you would say.

public class MyTextBox : TextBox

    {

        public MyTextBox():base()

        {

        }

        static MyTextBox()

        {

            FlowDirectionProperty.OverrideMetadata(typeof(MyTextBox), new FrameworkPropertyMetadata(new PropertyChangedCallback(FlowDirectionPropertyChanged)));

 

        }

 

        private static void FlowDirectionPropertyChanged(DependencyObject sender, DependencyPropertyChangedEventArgs args)

        {

            ((MyTextBox)sender).FontWeight = (((MyTextBox)sender).FlowDirection == FlowDirection.RightToLeft) ? FontWeights.Bold : FontWeights.Normal;

        }

    }

But hey, things get easy, thanks to Ben. What you can do is use the DependencyPropertyDescriptor. 

DependencyPropertyDescriptor dpd = DependencyPropertyDescriptor.FromProperty(DependencyProperty, typeof(Control)));
if (dpd != null)
{
    dpd.AddValueChanged(ControlInstance,
delegate
    {
       
// Add property change logic.
    });
}

 

So, as an example I just tried the following on a textbox. You change the flowDirection (Ctrl and Left Shift) and the text gets bold.... and yeah you need to have some RTL language such as Arabic installed. By default only English comes installed :)

DependencyPropertyDescriptor dpd = DependencyPropertyDescriptor.FromProperty(TextBox.FlowDirectionProperty, typeof(TextBox));
if (dpd != null)
{
    dpd.AddValueChanged(tb,
delegate
    {
        tb.FontWeight=(tb.FlowDirection==FlowDirection.RightToLeft)?FontWeights.Bold:FontWeights.Normal;

    });
}

 

That makes life a lot easier… doesn’t it!!

Share this post
Page 1 of 1 (8 items)