2021-08-13 WPF控件专题 ComboBox 控件详解
Posted 微软MVP Eleven
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了2021-08-13 WPF控件专题 ComboBox 控件详解相关的知识,希望对你有一定的参考价值。
1.ComboBox 控件介绍
-
手动添加项
-
绑定数据 代码里ItemSource IEnumerable List
Items.Add
-
DataContext =List ItemSource="{Binding}"
2.具体案例
<Grid>
<ComboBox HorizontalAlignment="Left" Margin="96,95,0,0" VerticalAlignment="Top" Width="190" Height="30" VerticalContentAlignment="Center" >
<ComboBoxItem Content="请选择" IsSelected="True"></ComboBoxItem>
<ComboBoxItem Content="软件班"></ComboBoxItem>
<ComboBoxItem Content="英语班"></ComboBoxItem>
<ComboBoxItem Content="数学班"></ComboBoxItem>
</ComboBox>
<ComboBox Name="cboClasses" HorizontalAlignment="Left" Margin="96,182,0,0" VerticalAlignment="Top" Width="190" Height="30" VerticalContentAlignment="Center" ItemsSource="{Binding}" SelectionChanged="CboClasses_SelectionChanged">
</ComboBox>
<Button Content="Button" HorizontalAlignment="Left" Margin="162,282,0,0" VerticalAlignment="Top" Width="75" Click="Button_Click"/>
</Grid>
/// <summary>
/// ComboBoxWindow.xaml 的交互逻辑
/// </summary>
public partial class ComboBoxWindow : Window
{
public ComboBoxWindow()
{
InitializeComponent();
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
//获取数据源
List<ClassInfo> list = GetClassInfos();
// cboClasses.ItemsSource = list;//指定数据源
cboClasses.SelectedValuePath = "ClassId";//项的值对应的属性名
cboClasses.DisplayMemberPath = "ClassName";//项的显示文本对应的属性名
cboClasses.DataContext = list;
//不能直接移除,也不能添加
//cboClasses.Items.Add(new ClassInfo()
//{
// ClassId = 4,
// ClassName = "软件班"
//});
//如果仍然要添加或移除其中的项??? 移除:先把ItemSource设置为null,然后通过list移除项,再重新指定ItemSource。
//cboClasses.ItemsSource = null;
//list.Add(new ClassInfo()
//{
// ClassId = 4,
// ClassName = "软件班"
//});
//cboClasses.ItemsSource = list;
//动态添加移除
//foreach(ClassInfo cinfo in list)
//{
// cboClasses.Items.Add(cinfo);
//}
}
/// <summary>
/// 获取班级列表
/// </summary>
/// <returns></returns>
private List<ClassInfo> GetClassInfos()
{
List<ClassInfo> list = new List<ClassInfo>();
list.AddRange(new ClassInfo[]
{
new ClassInfo()
{
ClassId=0,
ClassName="请选择"
},
new ClassInfo()
{
ClassId=1,
ClassName="计算机一班"
},
new ClassInfo()
{
ClassId=2,
ClassName="计算机二班"
},
new ClassInfo()
{
ClassId=3,
ClassName="商务英语一班"
},
new ClassInfo()
{
ClassId=3,
ClassName="商务英语二班"
}
});
return list;
}
private void Button_Click(object sender, RoutedEventArgs e)
{
cboClasses.Items.RemoveAt(1);
}
//选择项改变时
private void CboClasses_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
//MessageBox.Show((cboClasses.SelectedItem as ClassInfo).ClassName);
//当前选定的文本、改变前的选定文本
MessageBox.Show(cboClasses.Text);
}
}
/// <summary>
/// 班级信息实体
/// </summary>
public class ClassInfo
{
public int ClassId { get; set; }
public string ClassName { get; set; }
}
以上是关于2021-08-13 WPF控件专题 ComboBox 控件详解的主要内容,如果未能解决你的问题,请参考以下文章
2021-08-19 WPF控件专题 TabControl 控件详解
2021-08-17 WPF控件专题 Groupbox 控件详解