C# WinForm MVVM ComboBox数据绑定

时间:2024-07-13 19:55:32

一直没搞懂ComboBox数据绑定时,为什么SelectValue属性绑定无效,今天试了下,在绑定时加了个false和DataSourceUpdateMode解决,就此记录。

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.ComponentModel;
 

namespace WindowsFormsApp1
{
    public partial class Form1 : Form
    {
        ViewModel viewModel=new ViewModel();
        public Form1()
        {
            InitializeComponent();
            InitializeControl();
        }
        private void InitializeControl()
        {
            label1.DataBindings.Add(nameof(label1.Text), viewModel, nameof(viewModel.CmbSelectedValue));
            comboBox1.DataBindings.Add(nameof(comboBox1.DataSource), viewModel, nameof(viewModel.CmbDataSource));
            comboBox1.DataBindings.Add(nameof(comboBox1.SelectedValue), viewModel, nameof(viewModel.CmbSelectedValue),false,DataSourceUpdateMode.OnPropertyChanged ); //false代表绑定后不立刻更新,DataSourceUpdateMode指定数据源更新控件实际
            comboBox1.DisplayMember = "Column1";
            comboBox1.ValueMember = "Column2";
        }
    }

    internal class ViewModel : INotifyPropertyChanged
    {
        private Model model=new Model();
        public event PropertyChangedEventHandler PropertyChanged;
        protected void OnPropertyChanged(string propertyName) {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }
        public ViewModel()
        {
            CmbSelectedValue = "Initialize";
            CmbDataSource=new DataTable();
            CmbDataSource.Columns.Add("Column1");
            CmbDataSource.Columns.Add("Column2");
            CmbDataSource.Rows.Add("C1-1", "C1-2");
            CmbDataSource.Rows.Add("C2-1", "C2-2");

        }     
        public DataTable CmbDataSource { get { return model.CmbDataSource; } set { model.CmbDataSource = value; OnPropertyChanged(nameof(model.CmbDataSource)); } }
        public string CmbSelectedValue { get { return model.CmbSelectedValue; } set { model.CmbSelectedValue = value; OnPropertyChanged(nameof(model.CmbSelectedValue)); } }
    }
    internal class Model
    {
        public DataTable CmbDataSource { get; set; }
        public string CmbSelectedValue { get; set; }
    }
}