如何将Listview MaxHeight绑定到当前窗口高度?

wpf*_*ner 6 data-binding wpf

如何将Listview MaxHeight绑定到当前窗口高度?

我想限制高度让我们说3/4的窗户高度.

我怎样才能做到这一点?

Tab*_*ool 1

您可以使用转换器根据窗口高度计算高度,如下所示......

您需要将 Window.ActualHeight 传递给转换器 - 然后它将返回窗口高度乘以 0.75。如果出于某种原因,当转换器被击中时,Window.ActualHeight 为 null(或者您意外地传递了无法转换为 double 的内容),它将返回 double.NaN,这会将高度设置为汽车。

public class ControlHeightConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter,
                           System.Globalization.CultureInfo culture)
    {
        double height = value as double;

        if(value != null)
        {
            return value * 0.75;
        }
        else
        {
            return double.NaN;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

像这样将其绑定到您的控件...(显然这是 xaml 的一个非常精简的版本!)

<Window x:Name="MyWindow"
  xmlns:converters="clr-namespace:NamespaceWhereConvertersAreHeld">
  <Window.Resources>
    <ResourceDictionary>
      <converters:ControlHeightConverter x:Key="ControlHeightConverter"/>
    </ResourceDictionary>
  </Window.Resources>

  <ListView MaxHeight="{Binding 
        ElementName=MyWindow, Path=ActualHeight, 
        Converter={StaticResource ControlHeightConverter}}"/>
</Window>    
Run Code Online (Sandbox Code Playgroud)