Toggle List Box Display In WPF

匿名 (未验证) 提交于 2019-12-03 01:45:01

问题:

I have a List Box in my WPF app. Here is the xaml code:

  <ListBox Grid.Row="4" Grid.Column="1" Visibility="{Binding lbIsVisible}">         <ListBoxItem>             <CheckBox>                 <TextBlock>CITRUS EXPRESS</TextBlock>             </CheckBox>         </ListBoxItem>          <ListBoxItem>             <CheckBox>                 <TextBlock>APL CALIFORNIA</TextBlock>             </CheckBox>         </ListBoxItem>          <ListBoxItem>             <CheckBox>                 <TextBlock>IS JAPAN</TextBlock>             </CheckBox>         </ListBoxItem>     </ListBox>      <CheckBox Grid.Row="3" Grid.Column="1" VerticalAlignment="Center" x:Name="chkSelectVessel" Checked="chkSelectVessel_Checked">         <TextBlock Text="Select Vessel"></TextBlock>     </CheckBox>

I'm trying to toggle the visibility of the list box. Here is the C# code.

public partial class ConfigSetting : Window {     public string lbIsVisible { get; set; }      public ConfigSetting()     {         InitializeComponent();         DataContext = this;         lbIsVisible = "Hidden";     }      private void chkSelectVessel_Checked(object sender, RoutedEventArgs e)     {         this.lbIsVisible = "Visible";     } }

But it doesn't seem to work. Can any one point where I'm going wrong?

回答1:

You should use INotifyPropertyChanged Interface like this:

public partial class ConfigSetting : Window, INotifyPropertyChanged {     public event PropertyChangedEventHandler PropertyChanged;      private string lbIsVisible;      public string LbIsVisible     {         get { return lbIsVisible; }         set         {             if (lbIsVisible != value)             {                 lbIsVisible = value;                 OnPropertyChanged("LbIsVisible");             }         }     }      protected void OnPropertyChanged(string propertyName)     {         if (PropertyChanged != null)         {             PropertyChanged(this, new PropertyChangedEventArgs(propertyName));         }     }      public ConfigSetting()     {         InitializeComponent();         LbIsVisible = "Hidden";         DataContext = this;     }              private void chkSelectVessel_Checked(object sender, RoutedEventArgs e)     {         LbIsVisible = "Visible";     }      private void ChkSelectVessel_OnUnchecked(object sender, RoutedEventArgs e)     {         LbIsVisible = "Hidden";     } }

And in the XAML bind to LbIsVisible property:

<ListBox Visibility="{Binding LbIsVisible}">

Also add Unchecked event to your CheckBox :

<CheckBox Grid.Row="3" Grid.Column="1" VerticalAlignment="Center"    x:Name="chkSelectVessel" Checked="chkSelectVessel_Checked" Unchecked="ChkSelectVessel_OnUnchecked">


转载请标明出处:Toggle List Box Display In WPF
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!