我的WPF应用中有一个列表框。这是xaml代码:
<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 :(得分: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">