【问题标题】:Autosize inside a WrapPanel?在 WrapPanel 内自动调整大小?
【发布时间】:2014-03-06 07:38:21
【问题描述】:

需要有关 xaml 布局的帮助。

我有一个 Wrappanel,里面有两个元素。左边的 MainGrid 需要固定在 900 像素。第二个,AuxillaryDataScrollViewer,如果 WrapPanel 包裹它,我希望最小为 650,最大为 100%。这可能吗?

这是我目前得到的:

<Window x:Class="scratch.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="768" Width="1024">
    <Grid>
        <ScrollViewer>
            <WrapPanel>
                <Grid Width="900" Height="800" Background="Bisque"></Grid>
                <ScrollViewer HorizontalScrollBarVisibility="Visible" VerticalScrollBarVisibility="Hidden" Width="650">
                    <Grid Width="1500" Height="700" Background="Tomato"></Grid>
                </ScrollViewer>
            </WrapPanel>
        </ScrollViewer>
    </Grid>   
</Window>

谢谢!

编辑添加更多细节:

客户希望进行数据输入并在右侧面板中实时查看计算结果,但他实验室中的某些计算机只能具有 1280 像素宽度,因此他希望将结果包装到下方的那些计算机数据输入表单。

【问题讨论】:

  • 你想让这两个元素并排吗?
  • 如果显示器有分辨率,如果没有,我希望它换行。
  • 我测试了您的代码,它按您的预期工作。
  • 感谢您查看代码,它并不能完全满足我的需要,因为如果它被包装,它不会拉伸到整个页面宽度。

标签: wpf xaml


【解决方案1】:

由于需求定义非常明确,您可以简单地添加一个SizeChanged 处理程序,并根据容器的宽度手动设置第二个元素的宽度。如果容器小于 900 + 650,则将第二个元素拉伸到容器的 100%。

public MainWindow()
{
    SizeChanged += MainWindow_SizeChanged;
}

void MainWindow_SizeChanged(object sender, SizeChangedEventArgs e)
{
    double firstElementWidth = MainGrid.Width;                          // 900
    double secondElementMinWidth = AuxillaryDataScrollViewer.MinWidth;  // 650 

    double secondElementWidth;

    // if wrapped, stretch to the container
    if (e.NewSize.Width < firstElementWidth + secondElementMinWidth)
        secondElementWidth = e.NewSize.Width;
    // otherwise (not wrapped), fill the remainder of the first row
    else
        secondElementWidth = e.NewSize.Width - firstElementWidth;
}

显然,这是快速而肮脏的。如果您需要更强大的功能,那么我建议您编写一个符合您需要的约定的custom panel。 WrapPanel 无法将元素拉伸到整体宽度,但您没有理由不能设计这样的面板。

【讨论】:

  • 我想到了这一点,但不想在代码审查过程中因为错过了一个更简单/不太麻烦的解决方案而被嘲笑。谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-01-22
  • 1970-01-01
  • 2015-02-13
  • 1970-01-01
  • 1970-01-01
  • 2017-04-29
  • 1970-01-01
相关资源
最近更新 更多