WPF的ComboBox 有些时候不能满足用户需求,需要对数据内容和样式进行自定义,下面就简要介绍一下用数据模板(DataTemplate)的方式对ComboBox 内容进行定制:
原型设计如下: 步骤: 1、新建一个WPF应用程序WpfAppDemo(VS2012),并新建一个images文件夹(上传图片素材); 2、在主界面MainWindow.xaml文件中添加一个Label、ComboBox 和Button控件,如下图: 代码如下:15 6 35 367 8 31 32 33 349 10 3011 28 2912 2713 1614 15 17 20 21 22 2318 19 24 25 26
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using System.Threading.Tasks; 6 using System.Windows; 7 using System.Windows.Controls; 8 using System.Windows.Data; 9 using System.Windows.Documents;10 using System.Windows.Input;11 using System.Windows.Media;12 using System.Windows.Media.Imaging;13 using System.Windows.Navigation;14 using System.Windows.Shapes;15 16 17 namespace WpfAppDemo18 {19 ///20 /// MainWindow.xaml 的交互逻辑21 /// 22 public partial class MainWindow : Window23 {24 public MainWindow()25 {26 InitializeComponent();27 //初始化数据,并绑定28 LodData();29 }30 31 32 private void LodData()33 {34 IListcustomList = new List ();35 //项目文件中新建一个images文件夹,并上传了001.png,002.png,003.png36 customList.Add(new empoyee() { ID ="001", Name = "Jack" ,Image="images/001.png",Desc="this is good gay!"});37 customList.Add(new empoyee() { ID = "002", Name = "Smith", Image = "images/002.png", Desc = "this is great gay!" });38 customList.Add(new empoyee() { ID = "003", Name = "Json", Image = "images/003.png", Desc = "this is the bset gay!" });39 40 41 this.myColorComBox.ItemsSource = customList;//数据源绑定42 this.myColorComBox.SelectedValue = customList[1];//默认选择项43 44 }45 46 47 private void Button_Click(object sender, RoutedEventArgs e)48 {49 //显示选择的员工ID信息50 MessageBox.Show((this.myColorComBox.SelectedItem as empoyee).ID);51 }52 53 54 55 56 57 }58 //定义员工类59 public class empoyee60 {61 public string ID { get; set; }62 public string Name { get; set; }63 public string Image { get; set; }64 public string Desc { get; set; }65 66 }67 }
4、编译运行,如果运气不错的话,应该能看到如下的界面: