How to center an element in wpf canvas

后端 未结 4 1154
谎友^
谎友^ 2020-12-14 01:18

How can I center an element in wpf canvas using attached properties?

4条回答
  •  庸人自扰
    2020-12-14 02:00

    The only way I know to do this is to figure out the size of the canvas, and then set the properties based off that. This can be done using an event handler for SizeChanged on the canvas:

    parentCanvas.SizeChanged += new SizeChangedEventHandler(parentCanvas_SizeChanged);
    
    void parentCanvas_SizeChanged(object sender, SizeChangedEventArgs e)
    {
        parentCanvas.SetLeft(uiElement, (parentCanvas.ActualWidth - uiElement.ActualWidth) / 2);
        parentCanvas.SetTop(uiElement, (parentCanvas.ActualHeight - uiElement.ActualHeight) / 2);
    }
    

提交回复
热议问题