WPF数据绑定网格行可见性

3
我有一个窗口,其中包含一个类似表单的网格。该窗口不是我的,根据用户选择的上下文,有一个新要求不显示(即折叠)第4和第5行。
我能想到的两种方法是:
  1. 在行内容上使用一个转换器,它接受bool值并在值为true时折叠可见性。
  2. 在网格行高属性上使用一个转换器。
我更喜欢后者,但是不知道如何获取转换器的输入值。以下是转换器代码和绑定。请问有人能告诉我如何设置绑定以使其起作用吗?是否有更简便的方式?

转换器代码

[ValueConversion(typeof(GridLength), typeof(Visibility))]
public class GridLengthToCollapseVisibilityConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {

        if (value == null || parameter == null) return Binding.DoNothing;

        var result = (GridLength) value;
        bool shouldCollapse;
        Boolean.TryParse(parameter.ToString(), out shouldCollapse);
        return shouldCollapse ? new GridLength() : result;

    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotImplementedException(); }
}

绑定(这就是我卡住的地方)

假设我想让高度的值为30,除非绑定的ShowLastName属性为true。下面的绑定不正确,但应该怎么写呢?

 <RowDefinition Height="{Binding Source=30, Converter={StaticResource GridLengthToCollapseVisibilityConv},ConverterParameter=ShowLastName}" />

可行的解决方案

[ValueConversion(typeof(bool), typeof(GridLength))]
public class GridLengthToCollapseVisibilityConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {

        if (value == null || parameter == null) return Binding.DoNothing;

        bool shouldCollapse;
        Boolean.TryParse(value.ToString(), out shouldCollapse);
        return shouldCollapse 
            ? new GridLength(0) 
            : (GridLength) parameter;
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotImplementedException(); }

}

    <Grid.Resources>
        <cvt:GridLengthToCollapseVisibilityConverter x:Key="GridLengthToCollapseVisibilityConv" />
        <GridLength x:Key="AutoSize">Auto</GridLength>
        <GridLength x:Key="ErrorLineSize">30</GridLength>
    </Grid.Resources>

    <Grid.RowDefinitions>
        <RowDefinition Height="{StaticResource AutoSize}" />
        <RowDefinition Height="{StaticResource ErrorLineSize}" />
        <RowDefinition Height="{Binding Path=HideLastName, 
            Converter={StaticResource GridLengthToCollapseVisibilityConv},ConverterParameter={StaticResource AutoSize}}" />
        <RowDefinition Height="{Binding Path=HideLastName, 
            Converter={StaticResource GridLengthToCollapseVisibilityConv},ConverterParameter={StaticResource ErrorLineSize}}" />
    </Grid.RowDefinitions>

从你的帖子中学到了新东西... ValueConversion属性和Binding.DoNothing。谢谢。 - KornMuffin
2个回答

2

嘿,感谢您提出的切换值和参数的想法,这使得实现变得更容易。只要绑定到 DP(我以前做过),您就可以绑定 ConverterParameter。干杯! - Berryl

0

你所需要做的就是交换绑定和参数。


如果您仍然希望两个值都绑定到数据,即使第二个值是常量,请使用MultiBinding。这是一种hack方法,但它是将额外的值传递到转换器中最简单的方法。


顺便提一下,参数不能绑定,因为它不是 DP,没有机会。有一些标记扩展的技巧,但我不会走这条路。 - user572559

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接