XAML,C#:如何在Checkbox值切换时将ListView可见性设置为折叠/可见?

时间:2015-08-17 18:23:01

标签: c# xaml windows-10 win-universal-app windows-10-mobile

我是C#和Windows应用程序开发的新手,仅仅是为了学习目的,我正在尝试构建一个Windows 10通用应用程序。我正在试验Hub视图。

以下是我文件的Xaml结构。

   <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>

所以我要做的是分别使用Checkbox(1,2,3)切换ListView(2,3,4)的可见性。但在我的c#sharp代码中我无法访问我的XAML文件中定义的变量,我在复选框侦听器方法中尝试了FindName(),但它没有帮助。有什么方法可以获取数据或变量或绑定它们吗?

1 个答案:

答案 0 :(得分:2)

使用转换器概念:

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>