views:

149

answers:

3

hello, i have a wpf control that i'm developing.

this control contains and encapsulate another control.

i want to expose a property of the inner control to the window that consumes the control. i also want the inner control to perform logic when this property changed.

any suggestions?

A: 

just create wrapper property in the parent control. something like:

public int Value
{
get { return innerControl.Value; }
set { innerControl.Value = value; }
}

and the Value property of the inner control is a dependency property, then you should have everything you need (notifications, ...).

Martin Moser
Of course, if you did that, you wouldn't be able to use databinding or animation on the parent's property.
Joe White
+2  A: 

Both the inner and outer controls should define dependency properties. The template for the outer control should include the inner control, and should bind the properties together:

<local:InnerControl SomePropertyOnInnerControl="{TemplateBinding SomePropertyOnOuterControl}"/>

This ensures both your controls are independently usable and decoupled from eachother. The properties can be named according to their use in that control. For example, the inner control may call it something like Text whilst the outer control uses it for a more specific purpose like CustomerName.

HTH, Kent

Kent Boogaart
This is the correct approach; a proxy property is not a DependencyProperty and will not give you proper binding behavior.
AndyM
A: 

Dependency property updates are handled via property metadata, which is defined as part of your DependencyProperty. (It can also be added to existing DPs, but that's another topic.)

Define your DependencyProperty with metadata:

public static readonly DependencyProperty MyValueProperty =
    DependencyProperty.Register("MyValue", typeof(object), typeof(MyControl), 
    new UIPropertyMetadata(null, new PropertyChangedCallback(MyValue_PropertyChanged)));

Then implement your callback:

private static void MyValue_PropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
    MyControl c = (MyControl)d;
    c.DoSomething();
}
AndyM