匹配窗口大小的UserControl

本文关键字:UserControl 窗口大小 | 更新日期: 2023-09-27 18:17:23

我的应用程序是用WPF编写的。我有一个初始值为Width = 400的窗口。在那个窗口,我有一个DockPanel与StackPanel包含一个自定义UserControl称为ElementsPanel

代码如下:

<Window x:Class="Adiastemo2.EditWindow" ... Height="500" Width="400" x:Name="view2" ... >
    <DockPanel>
        <StackPanel Height="70" DockPanel.Dock="Top" Background="Beige">
            <local:ElementsPanel/>
        </StackPanel> ...

ElementsPanel控件由一个带有ListBox的StackPanel组成。ListBox的ItemsPanel是用一个简单的ScrollViewer和一个ItemsPresenter模板化的。

下面是代码:

<UserControl x:Class="Adiastemo2.ElementsPanel" ...
         xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
         mc:Ignorable="d" 
         d:DesignHeight="70">
<StackPanel Orientation="Horizontal" Margin="0,0,0,20" >
    <ListBox>
        <ListBox.ItemsPanel>
            <ItemsPanelTemplate>
                <VirtualizingStackPanel Orientation="Horizontal" Background="BlanchedAlmond"/>
            </ItemsPanelTemplate>
        </ListBox.ItemsPanel>
        <ListBox.Template>
            <ControlTemplate TargetType="ListBox">
                <ScrollViewer HorizontalScrollBarVisibility="Auto" VerticalScrollBarVisibility="Hidden">
                    <ItemsPresenter/>
                </ScrollViewer>
            </ControlTemplate>
        </ListBox.Template>
        ... <!-- Some test content comprising several 50x50 Buttons -->
    </ListBox>
</StackPanel>

我想让我的ElementsPanel和它的内容的宽度调整大小每当窗口调整大小,所以水平滚动是启用的,如果有太多的按钮要显示。现在我得到的是:

500x400窗口:http://screenshooter.net/100101493/qiaxocp

广泛:http://screenshooter.net/100101493/utkcyel

我如何实现我的目标?

匹配窗口大小的UserControl

将UserControl的 Width 绑定到Window的 ActualWidth

<Window x:Class="Adiastemo2.EditWindow" ... Height="500"
        Width="400" x:Name="view2" ... >
    <DockPanel>
        <StackPanel Height="70" DockPanel.Dock="Top" Background="Beige">
            <local:ElementsPanel Width="{Binding ActualWidth,
                                                 ElementName=view2}"/>
        </StackPanel> ...