举例说明该功能。
表单中有民族选项,分别为汉族和少数民族,当选择汉族时没有其他附加信息,当选择少数民族之后要弹出菜单继续选择是哪个少数民族
效果
实现代码
XAMl中
<Label Content="民族:" x:Name="label13" Width="Auto" Height="26" Grid.Column="2" Grid.Row="13" Margin="7,10,50,10"/>
<ListBox HorizontalAlignment="Left" x:Name="listBox2" SelectionMode="Single" VerticalAlignment="Center" SelectionChanged="listBox2_SelectionChanged" Grid.Column="3" Grid.Row="13" Height="26" Margin="7,10,0,10" Width="214" Grid.ColumnSpan="2">
<ListBoxItem HorizontalAlignment="Left" Content="汉族" Height="20" Width="88"/>
<ListBoxItem HorizontalAlignment="Left" Content="少数民族" Height="25" Width="108" />
</ListBox>
<StackPanel Orientation="Horizontal" Grid.Column="5" Grid.Row="13" Grid.ColumnSpan="2">
<ComboBox x:Name="comboBox1" Margin="5,10,0,10" Visibility="Collapsed">
<ComboBoxItem Content="蒙古族"/>
<ComboBoxItem Content="回族"/>
<ComboBoxItem Content="藏族"/>
<ComboBoxItem Content="维吾尔族"/>
<ComboBoxItem Content="苗族"/>
<ComboBoxItem Content="彝族"/>
<ComboBoxItem Content="壮族"/>
<ComboBoxItem Content="布依族"/>
<ComboBoxItem Content="朝鲜族"/>
<ComboBoxItem Content="满族"/>
<ComboBoxItem Content="侗族"/>
<ComboBoxItem Content="瑶族"/>
<ComboBoxItem Content="白族"/>
<ComboBoxItem Content="土家族"/>
<ComboBoxItem Content="哈尼族"/>
<ComboBoxItem Content="哈萨克族"/>
<ComboBoxItem Content="傣族"/>
<ComboBoxItem Content="黎族"/>
<ComboBoxItem Content="僳僳族"/>
<ComboBoxItem Content="佤族"/>
</ComboBox>
<Label x:Name="label19" Content="*" Foreground="Red" Grid.Column="6" Grid.Row="13"/>
</StackPanel>
以上代码是放在一个设置了行和列的Grid中。
然后在设计页面双击ListBox,跳转到ItemSelected事件
事件代码为
private void listBox2_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
comboBox1.Visibility = Visibility.Collapsed;
foreach (ListBoxItem li in listBox2.Items)
{
if ("少数民族".Equals(li.Content.ToString()) && li.IsSelected)
{
comboBox1.Visibility = Visibility.Visible;
}
}
}
检测ListBox中是否为少数民族选项被选中,是的话就设置隐藏的选项可见,否则不可见。
另外,Visibility的三个值Visible, Hidden,Collapsed,前两者好区分,而后两者都是将空间隐藏,其区别是Hidden是在不隐藏的基础上保留所占空间隐藏,而Collapsed是隐藏,并且不为隐藏空间留出空位。