简体   繁体   中英

Dependency Property correct usage

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?

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 .

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();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM