折叠其他列子项时调整WPF网格列的大小?

时间:2012-11-08 09:21:42

标签: wpf wpf-controls

我在Grid中有两个控件,需要在另一个Grid之后填充所有Collapseded空格,我不知道{{1}我可以使用,我也试过ContainerStackPanel,但我找不到一个好的解决方案。这是我的代码:

DockPanel

1 个答案:

答案 0 :(得分:3)

使用转换器怎么样?如

窗口资源中的

<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();
    }
}