简体   繁体   中英

Check if element is collapsed or visible

I want to check if a element is collapsed or visible so I can unhide or hide it but I keep getting the error

CS0029 Cannot implicitly convert type 'Windows.UI.Xaml.Visibility' to 'bool.

Code:

if (Test1.Visibility == Visibility.Visible)
{
    Test1.Visibility = Visibility.Collapsed;
}

Yes, you cant able to set true false directly in your control Visibility Property.

Visibility property accept only Visibility.Visible / Visibility.Hide / Visibility.collapsed

  1. Visible -> Given the Visibility to the control
  2. Hide -> Hide the Control but the Empty space(cap between the top & Bottom controls) is available
  3. Collapsed -> Hide the Control and remove the empty space.

If you want to assign the true/false value in your controls visibility you want to use the converter.

Converter Class:

public class BooleanToVisibilityConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        return (value is bool && (bool)value) ? Visibility.Visible : Visibility.Collapsed;
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

XAML:

First Add the Name space , second Add the Reference and Call converter into your control like below Text Box.

 <UserControl x:Class="WpfApplication1.UserControl1"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
             mc:Ignorable="d" 
            xmlns:local="clr-namespace:WpfApplication1"
             d:DesignHeight="300" d:DesignWidth="300">
    <UserControl.Resources>
        <local:BooleanToVisibilityConverter x:Key="boolToVisibilityConverter"/>
    </UserControl.Resources>
    <Grid>
        <TextBox Text="{Binding Name}" Visibility="{Binding IsVisibileName, Converter={StaticResource boolToVisibilityConverter}}" />
    </Grid>
</UserControl>

I try these code and I have no error

if (Test1.Visibility == Visibility.Visible)
 {
Test1.Visibility = Visibility.Collapsed;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM