Partilhar via


Listening to DependencyProperty changes

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

Comments

  • Anonymous
    March 07, 2007
    This is part of .net 3.0. You should have mentioned it.

  • Anonymous
    March 08, 2007
    Hi Mark, Thats a good point.. It is however mentioned in the tags :)

  • Anonymous
    March 18, 2007
    Appunti di WPF: Un po di link utili

  • Anonymous
    December 21, 2007
    Maybe not the best title to describe the post.  Anyway, I was looking at some of the apps the other...

  • Anonymous
    December 21, 2007
    Maybe not the best title to describe the post.  Anyway, I was looking at some of the apps the other...

  • Anonymous
    December 21, 2007
    Maybe not the best title to describe the post.  Anyway, I was looking at some of the apps the other...

  • Anonymous
    December 21, 2007
    Maybe not the best title to describe the post.  Anyway, I was looking at some of the apps the other...

  • Anonymous
    December 21, 2007
    Maybe not the best title to describe the post.  Anyway, I was looking at some of the apps the other...