我有一个简单的WrapPanel
其中包含一些广泛的控制。当我调整Window
的Width
时,一切正常。如果有足够的空间,则控件将在单行上传递,或者在没有足够空间时包装到下一行。WPF包装面板和滚动
但是,我需要发生的是,如果所有的控件基本上是垂直堆叠的(因为没有更多的水平空间)并且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
,你将无法看到按钮的文本。我想要一个水平滚动条出现,这样我就可以滚动查看文本,但不会干扰通常的包装功能。
谢谢。
更新: 我跟着保罗的建议下面和水平滚动条出现如预期现在。不过,我也想垂直滚动,所以我设置了VerticalScrollBarVisibility="Auto"
。问题是,如果我调整窗口大小以使垂直滚动条出现,即使不需要水平滚动条(水平空间足以查看整个控件),也会始终显示水平滚动条。看起来似乎垂直滚动条出现了与scrollviewer的宽度混乱。有没有办法纠正这个问题,除非实际需要水平滚动条?
下面是我的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吗? – hackerhasid 2010-01-22 17:26:36