wpf 如何在wpf画布中居中元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2208992/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 21:28:46  来源:igfitidea点击:

How to center an element in wpf canvas

wpfcanvaswpf-positioning

提问by Soham Dasgupta

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

如何使用附加属性将 wpf 画布中的元素居中?

采纳答案by mdm20

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

回答by Martin Braun

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.

我遇到了这篇文章,因为我正在寻找一种方法来仅在 XAML 中的画布中居中元素,而不是使用附加属性。

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>

回答by Robin

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 SizeChangedon the canvas:

我知道这样做的唯一方法是找出画布的大小,然后根据它设置属性。这可以使用SizeChanged画布上的事件处理程序来完成:

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

回答by mLar

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

您可以将 Canvas 和要居中的元素放在 Grid 中:

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