我有一个窗口,其中包含一个类似表单的网格。该窗口不是我的,根据用户选择的上下文,有一个新要求不显示(即折叠)第4和第5行。
我能想到的两种方法是:
我能想到的两种方法是:
- 在行内容上使用一个转换器,它接受bool值并在值为true时折叠可见性。
- 在网格行高属性上使用一个转换器。
转换器代码
[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>