2015-11-13 127 views
0

我在我的WPF應用程序中有一個列表框。這裏是xaml代碼:在WPF中切換列表框顯示

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

我想切換列表框的可見性。 這裏是C#代碼。

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"; 
    } 
} 

但它似乎沒有工作。任何一點我會出錯?

+0

你在哪裏被定義爲'chkSelectVessel_Checked'事件? –

+0

更新了xaml代碼 – iJade

回答

0

你應該使用INotifyPropertyChanged Interface這樣的:

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"; 
    } 
} 

而在XAML綁定到LbIsVisible屬性:

<ListBox Visibility="{Binding LbIsVisible}"> 

而且Unchecked事件添加到您的CheckBox

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

好大:) ... – iJade