Search code examples
c#xamlwindows-10win-universal-appwindows-10-mobile

XAML, C# : How to Set ListView Visibility to Collapse/Visible on Checkbox value toggle?


i am newbie in C# and Windows app development, just for learning purpose i am trying to build a Windows 10 universal app. I am experimenting with Hub view.

Below is the Xaml structure of my file.

   <Hub>
       <HubSection1>
       //SomeData here
       </HubSection1>

       <HubSection2>
          <DataTemplate>
          <Grid>
              <ListView1>
                         <CheckBox1>
                                   <ListView2>
                                        //SomeData here

                         <CheckBox2>
                                   <ListView3>
                                         //SomeData here

                         <CheckBox3>
                                   <ListView4>
                                         //SomeData here

              </ListView1>

           </Grid>
           </DataTemplate>

       </HubSection2>

       <HubSection3>
       //SomeData here
       </HubSection3>

       <HubSection4>
       //SomeData here
       </HubSection4>

    </Hub>

So what i am trying to do is to toggle the visibility of ListView(2,3,4) Using Checkboxes(1,2,3) respectively. But in my c# sharp code i am unable to access the variables defined in my XAML file, i tried FindName() in checkbox listeners Method but it didn't helped. is there any way i can fetch data or variables or bind them ??


Solution

  • Use converter concept:

    public class BooleanToVisibility : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            bool isChecked = false;
            if (bool.TryParse(value.ToString(), out isChecked))
            {
                return isChecked ? Visibility.Visible : Visibility.Collapsed;
            }
            return visibility;
        }
    
        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            return value;
        }
    }
    

    XAML:

    <Window x:Class="MyApp.Windows.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:converters="clr-namespace:MyApp.Converters">
        <StackPanel>
            <StackPanel.Resources>
                <converters:BooleanToVisibility x:Key="boolToVisibility"/>
            </StackPanel.Resources>
            <CheckBox Content="Check to see ListView" Name="changeVisibility"/>
            <ListView Visibility="{Binding Path=IsChecked, ElementName=changeVisibility, Converter={StaticResource boolToVisibility}}"/>
        </StackPanel>
    </Window>