如何绑定到组合框控件而无需向Winforms中的代码添加代码?

时间:2013-01-29 17:45:45

标签: c# winforms c#-4.0 data-binding combobox

我正在尝试找到一种最优雅的方式,可以在不使用代码的情况下绑定到Windows窗体上的组合框。在表格上我有一个带有两个绑定源的组合框。一个绑定到一个Controller,它包含一个国家列表,并在调用时填充此列表。另一个绑定源绑定到绑定到控制器的其他绑定源,我将数据成员设置为“Countries”的集合。我正在使用EF5来获取控制器中的数据。但是,根据我的工作,我无法在运行应用程序时填充组合框。请帮助我在数据绑定方面缺少什么?请在下面找到我的代码:

    static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            IUnityContainer container = new UnityContainer();
            Modules.RegisterModules(container);

            var controller = container.Resolve<IController>();
            Application.Run(new TestForm(controller));
        }
    }

    internal static class Modules
    {
        public static void RegisterModules(IUnityContainer container)
        {
            container.RegisterType<IController, GeoController>();
            container.RegisterType<IModelContainer, GeoModelContainer>();
        }
    }

    public class GeoController : IController, INotifyPropertyChanged
    {
        private List<Continent> _continents;
        private List<Country> _countries;
        private List<City> _cities;
        IModelContainer Container { get; set; }

        public GeoController(IModelContainer container)
        {
            Container = container;

            Countries = Container.Countries.ToList();
        }

        #region Properties    

        public List<Country> Countries
        {
            get { return _countries; }
            set
            {
                _countries = value;
                OnPropertyChanged();
            }
        }

        #endregion


        public event PropertyChangedEventHandler PropertyChanged;

        [NotifyPropertyChangedInvocator]
        protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
        {
            PropertyChangedEventHandler handler = PropertyChanged;
            if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
        }
    }

    public interface IController
    {
        List<Country> Countries { get; set; }
    }

    public partial class TestForm : Form
    {
        IController Controller { get; set; }
        public TestForm(IController controller)
        {
            InitializeComponent();

            Controller = controller;
        }
    }

0 个答案:

没有答案