内容不可见时隐藏列或行

时间:2017-04-10 12:33:13

标签: xaml xamarin xamarin.forms portable-class-library collapse

所以我有一个带有列的xaml Grid,当内容不可见时,我想隐藏或折叠列。

示例: 我有这个布局:

<Grid >      
    <Button Grid.Column="0" x:Name="FirstButton"  Text="First button" />      
    <Button Grid.Column="1"x:Name="SecondButton"  Text="Second button" />
</Grid>

当FirstButton不可见时,我想要这个结果

  <Grid >      
    <Button Grid.Column="1"x:Name="SecondButton"  Text="Second button" />
</Grid>

1 个答案:

答案 0 :(得分:11)

回答自己:

  <Grid>      
      <Grid.ColumnDefinitions>
        <ColumnDefinition Width="{Binding Path=IsVisible, Converter={StaticResource IsVisibleToGridLength}" BindingContext="{x:Reference Firstbutton}"   />
        <ColumnDefinition Width="{Binding Path=IsVisible, Converter={StaticResource IsVisibleToGridLength}" BindingContext="{x:Reference SecondButton}" />
  </Grid.ColumnDefinitions>

  <Button Grid.Column="0" x:Name="FirstButton"  Text="First button" />      
  <Button Grid.Column="1"x:Name="SecondButton"  Text="Second button" />
</Grid>

对于转换器部分

class IsVisibleToGridLengthConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo language)
    {
        try
        {
            GridUnitType t = GridUnitType.Star;
            if (parameter != null)
            {
                Enum.TryParse<GridUnitType>((string)parameter, true, out t);                    
            }

            if (value != null)
            {
                bool d = (bool)value;
                return d == false ? new GridLength(0,GridUnitType.Absolute) : new GridLength(1, t);
            }
            return null;
        }
        catch (Exception exp)
        {                
            return null;
        }
    }
    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo language)
    {
        return null;
    }
}

显然是App.xml部分

<Application  x:Class="MyNameSpace.App"
xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:class="clr-namespace:MyNameSpace.Class;assembly=MyNameSpace"/>
<Application.Resources>
  <ResourceDictionary>     
    <class:IsVisibleToGridLengthConverter  x:Key="IsVisibleToGridLength"/>   
  </ResourceDictionary>
</Application.Resources>
</Application>

希望它有所帮助!!