bizon
bizon

Reputation: 2414

How to create dependency property which get value from two other properties

I'm making animation of moving window on desktop. I have found somewhere info that the best way for this is creating own property and animate it instead of Left and Top separately.

The problem is that this property is initialized with value (0, 0). I want my property to get value from Top and Left of my window, and set it.

My property:

public static readonly DependencyProperty PositionProperty = DependencyProperty.Register("Position", typeof(Point), typeof(MainCard), 
        new PropertyMetadata(PositionPropertyChanged) );

private static void PositionPropertyChanged(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs prop)
{
    MainCard mw = (MainCard)dependencyObject;
    Point value = (Point)prop.NewValue;

    mw.Top = value.Y;
    mw.Left = value.X;
}

public Point Position
{
    get
    {
        return (Point)GetValue(PositionProperty);
    }
    set
    {
        SetValue(PositionProperty, value);
    }
}

Upvotes: 2

Views: 735

Answers (2)

Dan Bryant
Dan Bryant

Reputation: 27515

Check out MultiBinding and IMultiValueConverter. This will let you bind to two source properties and convert them into a single value for your Position.


EDIT: It sounds like what you really want to do here is animate a Point rather than seperate Left and Top values, so this probably doesn't apply to your case. The real problem here is that you have a two-way problem; this property represents the same information as Top and Left, so if you change it, then Top and Left should change. Likewise, since Top and Left are mutable, if those change, you really want your property to reflect that.

One option is to register a property changed handler for LeftProperty and TopProperty. Now, when those change, update your PositionProperty. You have to be careful here not to trigger repeated updates (I change Left, which changes Position, which changes Left, which...)

Upvotes: 1

David
David

Reputation: 6124

I don't really understand what you're trying to achieve but... here's my take on your question :

  • first, you can't put the "default" value for your property to the top/left values of your windows, since it is only know at runting, whereas the "default" value for the property must be provided at compilation time.
  • so basically, what you have to to is to set the value of your property right when you have it (for instance in the "show()" method of your window) like this :

    myMainCard.SetCurrentValue(MainCard.PositionProperty, new Point() { X = myWindow.Left, Y = myWindow.Top });

Upvotes: 1

Related Questions