Silverlight依赖属性更改事件问题

时间:2010-02-02 13:07:54

标签: silverlight custom-controls dependency-properties

我有一个具有Dependancy属性的自定义控件...它有一些,但让我们说Dragable是我的问题。该属性是一个布尔值,我希望每次更改时执行一段代码......一个切换。

我有两个选项,都显示在下面

[Category("Modal Options")]
    public bool Dragable
    {
        get { return (bool)GetValue(DragableProperty); }
        set { SetValue(DragableProperty, value); toggleDragable(); }
    }

    // Using a DependencyProperty as the backing store for Dragable.  This enables animation, styling, binding, etc...
    public static readonly DependencyProperty DragableProperty =
        DependencyProperty.Register("Dragable", typeof(bool), 
        typeof(PlussWindow), new PropertyMetadata(false));

    private void MakeDragable()
    {
        this.dragBehavior.Attach(this.LayoutRoot);
    }

    private void MakeUnDragable()
    {
        this.dragBehavior.Detach();
    }

    public virtual void toggleDragable()
    {
        if (this.Dragable)
        {
            MakeUnDragable();
        }
        else
        {
            MakeDragable();
        }
    }

[Category("Modal Options")]
    public bool Dragable
    {
        get { return (bool)GetValue(DragableProperty); }
        set { SetValue(DragableProperty, value); }
    }

    // Using a DependencyProperty as the backing store for Dragable.  This enables animation, styling, binding, etc...
    public static readonly DependencyProperty DragableProperty =
        DependencyProperty.Register("Dragable", typeof(bool), 
        typeof(PlussWindow), new PropertyMetadata(false, (o, e) => { (o as PlussWindow).toggleDragable(); } 
         ));

    private void MakeDragable()
    {
        this.dragBehavior.Attach(this.LayoutRoot);
    }

    private void MakeUnDragable()
    {
        this.dragBehavior.Detach();
    }

    public virtual void toggleDragable()
    {
        if (this.Dragable)
        {
            MakeUnDragable();
        }
        else
        {
            MakeDragable();
        }
    }

每个方法都会导致“对象引用未设置为对象的实例”

我通常使用绑定来解决这个问题,例如可见性或文本很容易完成,但对于自定义功能,我需要在代码中启用它。

我该怎么做,注意propertychanged方法是静态的?

1 个答案:

答案 0 :(得分:3)

试试这个:

public bool Dragable
    {
        get { return (bool)GetValue(DragableProperty); }
        set { SetValue(DragableProperty, value); }
    }

    public static readonly DependencyProperty DragableProperty =
        DependencyProperty.Register("Dragable", typeof(bool), typeof(PlussWindow), new PropertyMetadata(false, new PropertyChangedCallback(onDragableChange)));

    private static void onDragableChange(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        bool validate = (bool)e.NewValue;
        PlussWindow win = (PlussWindow) d;

        if (validate)
        {
            win.dragBehavior.Attach(this.LayoutRoot);
        }

        else
        {
            win.dragBehavior.Detach();
        }


    }