如何调整用户控件的大小



我的WPF应用程序中有一个UserControl。用户控件有一个列表框,可以是任何大小,下面是一些buttons

当我将我的 UserControl 放在我的一个视图中时,我希望它随着父级调整大小而垂直调整大小。但是,我希望列表框减少高度,而不是整个控件。这意味着在较小的屏幕上,按钮仍保留在屏幕上,但它们在 ListBox 中看不到太多内容。我可以使用最小高度来确保按钮和列表框中至少 1 个项目可见!

我发现了类似的问题,例如WPF用户控件不会使用主窗口调整大小,但我的代码没有任何高度或宽度

我的用户控件

<Grid>
    <StackPanel>
    <ListBox ItemsSource="{Binding MessageList" ></ListBox>
        <WrapPanel HorizontalAlignment="Center">
        <Button Content="Expand" HorizontalAlignment="Left" Margin="0,0,40,0"/>
        </WrapPanel>
    </StackPanel>
</Grid>

和风景

<Grid>
    <StackPanel>
        <uc:RecentList MessageList="{Binding Messages}" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" />
    </StackPanel>
</Grid>
无论

我如何调整视图大小,用户控件似乎都保持完全相同的大小。

我尝试了ViewBox但这正在扩展一切!

我也试过(在UserControl

<Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="*" />
        <RowDefinition Height="Auto" />
    </Grid.RowDefinitions>
    <ListBox ItemsSource="{Binding MessageList, RelativeSource={RelativeSource AncestorType=UserControl}}" Grid.Row="0"></ListBox>
        <WrapPanel Grid.Row="1" HorizontalAlignment="Center">
            <Button Content="Expand" HorizontalAlignment="Left" Margin="0,0,40,0"/>                
        </WrapPanel>
</Grid>

但没有区别。

StackPanel 不会沿其Orientation的方向拉伸其子元素。

因此,删除所有堆栈面板并在用户控件的网格中定义两行:

<Grid>
    <Grid.RowDefinitions>
        <RowDefinition />
        <RowDefinition Height="Auto" />
    </Grid.RowDefinitions>
    <ListBox Grid.Row="0" ItemsSource="{Binding MessageList ...}"/>
    <WrapPanel Grid.Row="1" HorizontalAlignment="Center">
        <Button Content="Expand" HorizontalAlignment="Left" Margin="0,0,40,0"/>
    </WrapPanel>
</Grid>

在主视图中:

<Grid>
    <uc:RecentList ... />
</Grid>

查看有关 MSDN 的面板概述文章。

最新更新