【发布时间】:2011-06-14 17:23:22
【问题描述】:
我有一个带有网格的窗口,其作用类似于表单。该窗口不是我自己的,并且有一个新要求,即根据用户选择的上下文不显示(即折叠)第 4 行和第 5 行。
要完成这项工作,我能想到的两件事是:
- 在行内容上有一个转换器,该转换器采用布尔值,如果为真则折叠可见性。
- 在网格行高属性上有一个转换器。
我更喜欢后者,但无法获得转换器的输入值。转换器代码和绑定如下。
谁能告诉我绑定应该是什么样子才能完成这项工作?有没有更简单的方法来做到这一点?
转换器代码
[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 属性为真。 下面的绑定不正确,那是什么?
<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。谢谢。
标签: wpf data-binding forms visibility