MaxHeight受限的可调整大小的ScrollViewer

时间:2018-10-24 10:16:17

标签: wpf xaml

我想用有限的MaxHeight实现可调整大小的ScrollViewer。 假设我们有一个ScrollViewer

<Grid Width="200"
      Margin="42 42 0 0">
    <Grid.RowDefinitions>
        <RowDefinition Height="Auto"/>
        <RowDefinition Height="400"/>
        <RowDefinition Height="10"/>
        <RowDefinition/>
    </Grid.RowDefinitions>

    <TextBlock Grid.Row="0"
               Text="ScrollViewer"/>

    <ScrollViewer Grid.Row="1"/>

    <GridSplitter Grid.Row="2"
                  HorizontalAlignment="Stretch"
                  ResizeDirection="Rows"/>
</Grid>

如何限制其MaxHeight,使其离Window底部的距离不能超过100px?窗口可以调整大小。

1 个答案:

答案 0 :(得分:0)

我有这个解决方案

<Grid Width="200"
      Margin="42 42 0 0">
    <Grid.RowDefinitions>
        <RowDefinition Height="Auto"/>
        <RowDefinition Height="400">
            <RowDefinition.MaxHeight>
                <MultiBinding Converter="{StaticResource MaxScrollViewerHeightConverter}">
                    <Binding RelativeSource="{RelativeSource FindAncestor, AncestorType=Window}" Path="ActualHeight"/>
                    <Binding ElementName="ScrollViewer"/>
                    <Binding RelativeSource="{RelativeSource FindAncestor, AncestorType=Window}"/>
                </MultiBinding>
            </RowDefinition.MaxHeight>
        </RowDefinition>
        <RowDefinition Height="10"/>
        <RowDefinition/>
    </Grid.RowDefinitions>

    <TextBlock Grid.Row="0"
               Text="ScrollViewer"/>

    <ScrollViewer Grid.Row="1"
                  Name="ScrollViewer"/>

    <GridSplitter Grid.Row="2"
                  HorizontalAlignment="Stretch"
                  ResizeDirection="Rows"/>
</Grid>

还有转换器:

public class MaxScrollViewerHeightConverter : IMultiValueConverter
{
    /// <summary>
    /// Convert
    /// </summary>
    public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
    {
        var actualWindowHeight = (values[0] as double?) ?? 0.0;

        if (values[1] is UIElement scrollViewer && values[2] is UIElement window)
        {
            const double bottomOffset = 100;

            var relativeVerticalPosition = scrollViewer.TranslatePoint(new Point(0, 0), window).Y;
            return actualWindowHeight - relativeVerticalPosition - bottomOffset;
        }

        return actualWindowHeight;
    }

    /// <summary>
    /// Convert back not implemented
    /// </summary>
    public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

但是我不喜欢将窗口传递给转换器的想法,所以我试图找到更优雅的解决方案。