ComboBox在WPF中的绑定示例:绑定项、集合、转换,及其源代码

2021-05-01 06:26

阅读:601

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.ComponentModel;

namespace ComboBoxBindings
{
    /// 


    /// Interaction logic for Window1.xaml
    /// 

    public partial class Window1 : Window
    {
        private int index;
        
        public Window1()
        {
            InitializeComponent();

            dogs.Add(new Dog("Dog1"));
            dogs.Add(new Dog("Dog2"));
            dogs.Add(new Dog("Dog3"));

            types.Add("EducationGrade1");
            types.Add("EducationGrade2");
            types.Add("EducationGrade3");

            this.listView1.ItemsSource = persons;
        }

        public List types = new List();
        public List EducationTypes
        {
            get
            {
                return types;
            }
        }

        public BindingList dogs = new BindingList();
        public BindingList Dogs
        {
            get
            {
                return dogs;
            }
        }

        public BindingList persons = new BindingList();
        public BindingList Persons
        {
            get
            {
                return persons;
            }
        }

        private void comboBoxInListView_Loaded(object sender, RoutedEventArgs e)
        {
            ComboBox box = sender as ComboBox;
            box.ItemsSource = null;
            box.ItemsSource = dogs;
        }

        private void btnAdd_Click(object sender, RoutedEventArgs e)
        {
            persons.Add(new Person(++index));
        }

        private void btnDel_Click(object sender, RoutedEventArgs e)
        {
            while (this.listView1.SelectedItems.Count > 0)
            {
                persons.Remove((Person)this.listView1.SelectedItems[0]);
            }
        }

        private void comboBoxInWnd_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            ComboBox box = sender as ComboBox;

            this.stackPanel1.DataContext = null;
            this.stackPanel1.DataContext = box.SelectedItem;
        }
    }
}


评论


亲,登录后才可以留言!