【问题标题】:How to resize UserControl如何调整用户控件的大小
【发布时间】:2016-02-03 15:35:15
【问题描述】:

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

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

我发现了类似的问题,例如WPF user control does not resize with main window,但我的代码没有任何高度或宽度

我的用户控件

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

无论我如何调整视图大小,UserControl 似乎都保持完全相同的大小。

我尝试了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>

但没有区别。

【问题讨论】:

    标签: wpf xaml


    【解决方案1】:

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

    所以删除所有 StackPanel 并在 UserControl 的 Grid 中定义两行:

    <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 上的 Panels Overview 文章。

    【讨论】:

    • 此更改没有产生任何影响 :(
    • 您是否也从主视图中删除了 StackPanel?
    • 这太奇怪了,你知道那是我做错了什么......巫术!!!嘿嘿嘿谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-04-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-30
    • 1970-01-01
    相关资源
    最近更新 更多