How to center an element in wpf canvas

吃可爱长大的小学妹 提交于 2019-11-27 12:11:32

问题


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


回答1:


Something like this.

double left = (Canvas.ActualWidth - element.ActualWidth) / 2;
Canvas.SetLeft(element, left);

double top  = (Canvas.ActualHeight - element.ActualHeight) / 2;
Canvas.SetTop(element, top);



回答2:


I came across this post, because I was searching for a way to center an element within a Canvas in XAML only, instead of using Attached Properties.

Just in case, you came for the same reason:

<Canvas x:Name="myCanvas">
    <Grid Width="{Binding ActualWidth, ElementName=myCanvas}" 
          Height="{Binding ActualHeight, ElementName=myCanvas}">
        <Label Content="Hello World!"
               HorizontalAlignment="Center"
               VerticalAlignment="Center" 
        />
    </Grid>
</Canvas>



回答3:


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);
}



回答4:


You can put the Canvas and the element you want to be centered inside a Grid :

<Grid>
    <Canvas Width="200" Height="200" Background="Black" />
    <Button Width="50" Height="20" > Hello
    </Button>
</Grid>


来源:https://stackoverflow.com/questions/2208992/how-to-center-an-element-in-wpf-canvas

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!