views:

125

answers:

2

My code currently looks like this:

private Foo myFoo;

public Foo CurrentFoo
{
    get { return myFoo; }
    set { SetFoo(value); }
}

private void SetFoo(Foo newFoo)
{
    // Do stuff
    // Here be dragons

    myFoo = newFoo;
}

To be able to bind it in XAML/WPF I need to turn Foo into a dependency property:

public static DependencyProperty CurrentFooProperty = 
    DependencyProperty.Register("CurrentFoo", typeof(Foo), 
        typeof(FooHandler), new PropertyMetadata(false));        

public Foo CurrentFoo
{
    get { return (Foo)GetValue(CurrentFooProperty); }
    set { SetValue(CurrentFooProperty, value); }
}

Ive heard that you shouldnt do magic inside the actual C# property set {}, since it might not be called but the value is written directly to the dependency property. If this is false, let me know, it seems like the most obvious and simple route to take.

I know I can add a validation function to the dependency property but I assume that it shouldnt be used for this? I need to communicate the change to legacy systems that cannot yet be bound in XAML.

Whats the best way to approach this problem?

+3  A: 
public static DependencyProperty CurrentFooProperty = DependencyProperty.Register(
    "CurrentFoo",
    typeof(Foo), 
    typeof(FooHandler),
    new PropertyMetadata(OnCurrentFooChanged));

private static void OnCurrentFooChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
    var currentFoo = (Foo) e.NewValue;

    // Use
}
Bryan Watts
+1  A: 

This should be handled by a callback assigned to the Dependency Property. The proper place for this depends on what is actually happening here:

// Do stuff
// Here be dragons

There are three callbacks that can be assigned to a Dependency Property - If you just need to notify the legacy systems, then I recommend adding a Property Changed callback, and adding the notification there.

If, however, this is performing something that amounts to validation via the Legacy system, it may be more appropriate to put these dragons into the ValidationCallback.

I doubt that the CoerceValue callback is appropriate, given your scenario.

Reed Copsey