我有一個簡單的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