以WPF控件为中心

时间:2009-08-21 19:58:04

标签: wpf layout fill

我有一个窗口,我在其中添加一个新的UserControl(带图像),我只想将控件置于屏幕中间(垂直和水平)。我只能让垂直的工作。我将从我的CodeBehind交换DockPanel中的内容,并希望在我开始播放幻灯片UI之前显示此启动屏幕,这意味着内容是从CodeBehind设置的。

我的Window

<Window x:Class="GreenWebPlayerWPF.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Window1" Height="512" Width="853" WindowStyle="None" WindowState="Maximized" WindowStartupLocation="CenterScreen">
    <DockPanel Width="Auto" Height="Auto" Name="TransitionContainer" Background="Black" Margin="0" LastChildFill="True"></DockPanel>
</Window>

我的UserControl

<UserControl x:Class="GreenWebPlayerWPF.FrontPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <DockPanel Background="Black">
        <Image Name="image1" Stretch="None" Source="/GreenWebPlayerWPF;component/gw.png" />
    </DockPanel>
</UserControl>

请注意我使用的是最大化/全屏。

3 个答案:

答案 0 :(得分:12)

使用Grid

  <Grid>  
    <Grid.ColumnDefinitions>
      <ColumnDefinition Width="*"/>
      <ColumnDefinition Width="Auto"/>
      <ColumnDefinition Width="*"/>
    </Grid.ColumnDefinitions>
    <Grid.RowDefinitions>
      <RowDefinition Height="*"/>
      <RowDefinition Height="Auto"/>
      <RowDefinition Height="*"/>
    </Grid.RowDefinitions>
    <!-- Replace with your UserControl -->
    <Button Content="Foo" Grid.Column="1" Grid.Row="1"/>
  </Grid>

您可以将其停靠在DockPanel内(如果您必须有DockPanel)以进行拉伸。当然,虽然以上都是标记,但您可以轻松地从代码中创建这样的网格。

答案 1 :(得分:3)

在尝试将页面中的元素居中时,我一直遇到此问题。 StackPanel的问题是,当Orientation为Horizo​​ntal时,Horizo​​ntalAlignment无效,而当Orientation为Vertical时,VerticalAlignment无效。所以你一直在试图设置值没有任何影响。它以这种方式工作并不是不合逻辑的,但如果将其报告为错误则会很好。

我找到的解决方案是有两个叠加的StackPanel,一个水平居中,另一个垂直放置,如下图所示。找到父级的大小需要调整中间面板的大小,否则它将是平的并且其内容是隐藏的 - 绝对值也可以。虽然不是灵丹妙药,但它比使用网格要简单得多。

<StackPanel Background="Bisque" Orientation="Vertical" Width="300" Height="300" >
    <StackPanel HorizontalAlignment="Center"  Orientation="Horizontal"
                  Height="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType=StackPanel}, Path=ActualHeight}">
        <StackPanel VerticalAlignment="Center" Width="200" Height="60" Background="Blue">
        </StackPanel>
    </StackPanel>
</StackPanel>

答案 2 :(得分:0)

它已经很老了,但是现在居中放置控件就像这样简单:

<Grid VerticalAlignment="Stretch" HorizontalAlignment="Stretch">

    <StackPanel VerticalAlignment="Center" HorizontalAlignment="Center" Height="350" Width="600">
        <TextBox />
    </StackPanel>

</Grid>