【发布时间】:2011-01-08 07:22:34
【问题描述】:
我有一个简单的WrapPanel,其中包含许多宽控件。当我调整Window 的Width 的大小时,一切都按预期工作。如果有足够的空间,这些控件将在一行上穿过,或者在没有空间时折回到下一行。
但是,我需要发生的是,如果所有控件基本上垂直堆叠(因为没有更多的水平空间)并且Window 的Width 减少了更多,则会出现水平滚动条这样我就可以滚动并查看整个控件,如果我愿意的话。下面是我的xaml。我尝试将WrapPanel 包装在ScrollViewer 中,但我无法实现我的目标。
<Window x:Class="WpfQuotes.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1" Height="Auto" Width="600" Foreground="White">
<WrapPanel>
<Button Width="250">1</Button>
<Button Width="250">2</Button>
<Button Width="250">3</Button>
</WrapPanel>
</Window>
因此,如果您将上述Window 的Width 减少到最小,您将无法看到按钮的文本。我希望出现一个水平滚动条,以便我可以滚动查看文本,但不会干扰通常的换行功能。
谢谢。
更新:
我遵循了 Paul 在下面的建议,水平滚动条现在按预期出现。但是,我还希望可以使用垂直滚动,所以我设置了VerticalScrollBarVisibility="Auto"。问题是,如果我调整窗口大小以显示垂直滚动条,水平滚动条也总是出现,即使它不需要(有足够的水平空间来查看整个控件)。似乎出现的垂直滚动条弄乱了滚动查看器的宽度。有没有办法纠正这个问题,除非确实需要,否则水平滚动条不会出现?
下面是我的 xaml,也是我在CustomWrapPanel 中添加的唯一代码:
<Window x:Class="Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:cwp="clr-namespace:CustomWrapPanelExample"
Title="Window1" Height="Auto" Width="300" Foreground="White" Name="mainPanel">
<ScrollViewer x:Name="MyScrollViewer" HorizontalScrollBarVisibility="Auto"
VerticalScrollBarVisibility="Auto">
<cwp:CustomWrapPanel Width="{Binding ElementName=MyScrollViewer, Path=ActualWidth}">
<Button Width="250">1</Button>
<Button Width="250">2</Button>
<Button Width="250">3</Button>
<Button Width="250">4</Button>
<Button Width="250">5</Button>
<Button Width="250">6</Button>
<Button Width="250">7</Button>
<Button Width="250">8</Button>
<Button Width="250">9</Button>
</cwp:CustomWrapPanel>
</ScrollViewer>
</Window>
CustomWrapPanel 中唯一被覆盖的东西:
protected override Size MeasureOverride(Size availableSize)
{
double maxChildWidth = 0;
if (Children.Count > 0)
{
foreach (UIElement el in Children)
{
if (el.DesiredSize.Width > maxChildWidth)
{
maxChildWidth = el.DesiredSize.Width;
}
}
}
MinWidth = maxChildWidth;
return base.MeasureOverride(availableSize);
}
【问题讨论】:
-
你能用 ScrollViewer 发布 XAML 吗?