views:

67

answers:

4

I have next dependecy property:

public static DependencyProperty IsInReadModeProperty =
    DependencyProperty.Register("IsInReadMode", typeof(bool),
    typeof(RegCardSearchForm), new PropertyMetadata(false, ReadModeChanged));

and I have next method which handle Property changed event:

public static void ReadModeChanged(DependencyObject d,
    DependencyPropertyChangedEventArgs e)
{
    if ((bool)e.NewValue)
    {       
        btnSearch.Visibility = Visibility.Collapsed;
        btnExport.Visibility = Visibility.Collapsed;
        cbExportWay.Visibility = Visibility.Collapsed;
    }
}

But compiler give me error that i cannot acces non static buttons (btnSearch and e.t.c ) in static context.

I want change visibility of buttons when property value changed. How can I resolve this situation?

A: 

If ReadModeChanged is a static method of the container for your buttons, then just make it an instance method of the container.

Matt Ellen
+1  A: 

One way could be to extend a class from DependencyObject that would contain the set/get of the controls that you want to manipulate. And process it in ReadModeChanged event by accessing DependencyObject.

This example might help.

... example derives from DependencyObject to create a new abstract class. The class then registers an attached property and includes support members for that attached property.

KMan
+1  A: 

Since (non-attached) DependencyProperties are restricted to being set on their owner type you can just create an instance method to hold your logic and call that from the static method by casting the DependencyObject:

public static readonly DependencyProperty IsInReadModeProperty = DependencyProperty.Register(
    "IsInReadMode",
    typeof(bool),
    typeof(RegCardSearchForm),
    new UIPropertyMetadata(false, ReadModeChanged));

private static void ReadModeChanged(DependencyObject dObj, DependencyPropertyChangedEventArgs e)
{
    RegCardSearchForm form = dObj as RegCardSearchForm;
    if (form != null)
        form.ReadModeChanged((bool)e.OldValue, (bool)e.NewValue);
}

protected virtual void ReadModeChanged(bool oldValue, bool newValue)
{
    // TODO: Add your instance logic.
}
John Bowen
A: 

These things do have to be static in order for a DependencyProperty to work properly However, the parameter to your PropertyChanged handler is probably the thing you need: it's the instance whose property has just changed. I suspect this would work for you:

public static void ReadModeChanged(DependencyObject d,
   DependencyPropertyChangedEventArgs e)
{
    if ((bool)e.NewValue)
    {
        RegCardSearchForm c = (RegCardSearchForm)d;
        c.btnSearch.Visibility = Visibility.Collapsed;
        c.btnExport.Visibility = Visibility.Collapsed;
        c.cbExportWay.Visibility = Visibility.Collapsed;
    }
}
Dan Puzey