我有一个简单的WrapPanel
,其中包含许多广泛的控件。当我调整大小Width
时,Window
一切都按预期工作。如果有足够的空间,控件将在单行上穿过,或者在没有空间时回绕到下一行。
但是,我需要发生的是,如果所有控件基本上都是垂直堆叠的(因为没有更多的水平空间)并且 的Width
减少Window
更多,出现一个水平滚动条,以便我可以滚动并查看整个如果我想控制。下面是我的xaml。WrapPanel
我尝试将a包裹起来,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>
因此,如果您将Width
上述内容减少Window
到最小,您将无法看到按钮的文本。我希望出现一个水平滚动条,以便我可以滚动查看文本,但不会干扰通常的换行功能。
谢谢。
更新:
我遵循了 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);
}