简体   繁体   中英

WPF Canvas scale transform translate

I'm currently facing a problem with ItemsControl and canvas in WPF.

What I'm trying to do :

  • Add Points to an ItemsControl and store their coordinates as a percentage/fraction relative to this ItemsControl size
  • Load them in another ItemsControl with their coordinates as percentage of this new ItemsControl

Example of what I want to achieve :

  • ItemsControl ContainerA is a square of 100 by 100. I add a new Point P1 at X=10 and Y=10.

  • I save P1 with X=0.1 and Y=0.1 (10% of ContainerA size)

  • I load P1 in ItemsControl ContainerB , a square of 500 by 500, P1 coordinates should be x=50 and Y=50 (10% of ContainerB size)

How would one accomplish this ?

Knowing that converters are not an option, and neither is ScaleTransform as my Points may help to display text / pictures / whatever and I don't want them to be scaled with the new container.

Any hint would be greatly appreciated

I managed to obtain what I wanted by creating a custom ItemsControl and an interface IScalableVm.

public class ScaleItemsControl : ItemsControl
{
    protected override void OnItemsChanged(NotifyCollectionChangedEventArgs e)
    {
        base.OnItemsChanged(e);
        ScaleItems();
    }

    protected override void OnRenderSizeChanged(SizeChangedInfo sizeInfo)
    {
        base.OnRenderSizeChanged(sizeInfo);
        ScaleItems();
    }

    private void ScaleItems()
    {
        foreach (var item in ItemsSource.OfType<IScalableVm>())
        {
            item.Scale(this.RenderSize.Width, this.RenderSize.Height);
        }
    }
}

Then I just scale the coordinates of my IScaleVms (my points for example) by multiplying their coordinates with the new width and height of this container.

public virtual void Scale(double width, double height)
{
    Position = new Point(width * _model.StartPosition.X, height * _model.StartPosition.Y);
}

It's far from being perfect. I still believe there is a way to do this in pure WPF style, but I don't know it

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