使用转换器怎么样?如
在窗口资源中
<Window.Resources>
<local:VisibilityToColumnLengthConverter x:Key="visConv" />
</Window.Resources>
......
<Grid >
<Grid.ColumnDefinitions>
<ColumnDefinition Width="{Binding ElementName=tb1, Path=Visibility, Converter={StaticResource visConv}}"/>
<ColumnDefinition Width="{Binding ElementName=tb2, Path=Visibility, Converter={StaticResource visConv}}"/>
</Grid.ColumnDefinitions>
<TextBox Grid.Column="0" Visibility="collapsed" Name="tb1" />
<TextBox Grid.Column="1" Visibility="Visible" Name="tb2" />
</Grid>
最后转换器的代码是
[ValueConversion(typeof(System.Windows.Visibility), typeof(System.Windows.GridLength))]
public class VisibilityToColumnLengthConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
System.Windows.Visibility vis = (System.Windows.Visibility)value;
if (vis == System.Windows.Visibility.Visible)
return new System.Windows.GridLength(1, System.Windows.GridUnitType.Star);
else
return new System.Windows.GridLength(1, System.Windows.GridUnitType.Auto);
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}