วิธีการตั้งค่าความสูงของ WPF ScrollViewer แบบไดนามิก

ฉันมีตัวอย่างทดสอบต่อไปนี้:

<Window x:Class="WpfScrollTest.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Window1" Height="200" Width="200">
    <Border>
        <StackPanel>
            <Label Width="Auto" Height="Auto" Content="Text to mess up the scrollview"/>
                <ScrollViewer Height="{Binding RelativeSource={RelativeSource FindAncestor, 
                        AncestorType={x:Type Border}}, Path=ActualHeight}">
                    <StackPanel>
                        <Button MinWidth="100" MinHeight="100" Content="Button"/>
                        <Button MinWidth="100" MinHeight="100" Content="Button"/>
                    </StackPanel>
                </ScrollViewer>
            </StackPanel>
    </Border>
</Window>

ซึ่งสร้างสิ่งนี้:

ด้านล่างของแถบเลื่อนหายไป

คำถามของฉันคือฉันจะตั้งค่า ScrollViewer.Height แบบไดนามิกในขณะที่ยังคงเห็นด้านล่างของแถบเลื่อนได้อย่างไร ในตัวอย่างของฉัน Height ของ ScrollViewer ยาวเกินไปเนื่องจาก Label อยู่ด้านบน ..

ฉันไม่ต้องการแก้ไข Height ของ ScrollViewer เป็นค่าคงที่


person Andrew Keith    schedule 19.10.2009    source แหล่งที่มา


คำตอบ (1)


ฉันอยากจะแนะนำให้ลบ StackPanel ภายนอกออกจาก Grid เนื่องจาก Stackpanel จะไม่เคารพขนาดของลูก และลบการเชื่อมโยง ScrollViewer.Height ตอนนี้คุณเพียงแค่ต้องสร้าง RowDefinition สองอันสำหรับ Grid และวาง Label ไปที่ Grid.Row=0 และ ScrollViwer ไปที่ Grid.Row=1

รหัสอยู่ด้านล่าง เคล็ดลับของฉันคือ ใช้ StackPanel/Canvas เฉพาะเมื่อจำเป็นเท่านั้น และอาจใช้สำหรับระดับภายใน พยายามใช้ Grid ให้มากขึ้นเพื่อให้ได้เลย์เอาต์ที่ไดนามิกมาก

  <Border>
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="*"/>
        </Grid.RowDefinitions>
        <Label Grid.Row="0" Width="Auto" Height="Auto" Content="Text to mess up the scrollview"/>
        <ScrollViewer Grid.Row="1" >
            <StackPanel>
                <Button MinWidth="100" MinHeight="100" Content="Button"/>
                <Button MinWidth="100" MinHeight="100" Content="Button"/>
            </StackPanel>
        </ScrollViewer>
    </Grid>
</Border>
person Jobi Joy    schedule 19.10.2009
comment
เฮ้ นั่นได้ผล ตอนนี้ฉันเห็นแล้วว่าเนื่องจาก RowDefinition สำหรับ ScrollViewer คือ * ดังนั้นจึงมีขนาดที่กำหนดไว้และใช้งานได้ ขอบคุณ :) - person Andrew Keith; 20.10.2009