如何使StackPanel适合其儿童宽度

本文关键字:何使 StackPanel | 更新日期: 2023-09-27 18:32:32

我在这里写下是因为我对这件事有很多问题,我希望你能帮助我解决:P

我想创建一个适合其所有子宽度的动态 StackPanel。我给你举个例子。

假设我的 StackPanel 当前是空的。它的宽度将为 10 (f.e.(,其固定高度为 30。然后我想添加一个图像,我写下了这个:

BitmapImage myImage = new BitmapImage(new Uri("[PATH]"));
Image realImage = new Image();
realImage.Source = myImage;
realImage.Width = 50;
realImage.Height = myImage.Height;
myStackPanel.Children.Add(realImage);

不过,StackPanel 并没有放大到 50px;它粘在 10px,剪切了我的图像。 当我尝试添加其他 UI 元素(如 TextBlocks 等(时,也会发生同样的情况。

我试图做类似的事情

myStackPanel.Width += realImage.Width;

但当然没有用。我试图将StackPanel的宽度设置为"自动",但它也没有帮助。这是 XAML 中的 StackPanel 声明:

<Window x:Name="MainWindow1" x:Class="Proj.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="myTitle" Height="480" Width="640"
    Loaded="onLoad" Background="Black" MinHeight="480" MinWidth="640">
    <Grid>
        ...(Other Closed Tags)...
        <StackPanel Orientation="Horizontal" Name="myStackPanel" Height="30" Margin="135,283,458,147"/>
    </Grid>
</Window>

我需要一个 StackPanel,因为我必须显示一个动态栏,其中包含可变数量的对象,这些对象将在屏幕上执行选框效果,从右向左滑动。我既不知道对象的数量,也不知道动态栏的最终宽度。

当然,如果你知道还有其他方法可以做到这一点,我会很高兴了解它:)

谢谢!

如何使StackPanel适合其儿童宽度

将堆栈面板放入 ScrollViewer 并将其宽度设置为"自动":

    <ScrollViewer HorizontalScrollBarVisibility="Auto">
        <StackPanel  Width="Auto">
            ....
        </StackPanel>
    </ScrollViewer>

我刚刚检查过,是的,你的问题Margin.请勿在布局中使用Margin进行绝对定位。 Margin应用作父控件的边距偏移量,但在尝试定位元素(如将项放在窗体中心(时应避免使用,因为它将元素剪裁到特定边界。

使用

auto宽度StackPanel可以轻松实现您想要的效果

<StackPanel Orientation="Horizontal" Name="myStackPanel" Height="30">
        <Button>Hello</Button>
        <Button>World</Button>
</StackPanel>

显然 - 如果您需要将其放置在窗口中的特定位置,则需要确保它具有完整的容器宽度 - 使用HorizontalAlignmentGrid来放置控件

从你的布局中,我会建议更像这样的东西:

<Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="1.4*"></RowDefinition>
        <RowDefinition Height="30"></RowDefinition>
        <RowDefinition Height="*"></RowDefinition>
    </Grid.RowDefinitions>
    <StackPanel Orientation="Horizontal" Grid.Row="1" Name="myStackPanel">
        <Button>Hello</Button>
        <Button>World</Button>
    </StackPanel>
</Grid>

除非绝对必要,否则我会避免为元素提供显式大小 - 如果您的父容器可以指定大小,那就更好了

如果您希望图像在StackPanel内水平对齐,则可以将HorizontalAlignment设置为Center