WinForms: Respond to BindingSource being applied

前端 未结 2 957
眼角桃花
眼角桃花 2020-12-11 07:39

Is there an event that I can latch onto to be notified when the datasource has been applied to its bound controls?

Or is there another event, in which I am guarantee

2条回答
  •  悲&欢浪女
    2020-12-11 08:29

    Data binding should already been activated before your form load event. The problem you are experiencing is because due to to data binding infrastructure optimization, binding does not happen for invisible controls until they become visible for a first time. This is probably because the designers of WF were thinking that the data binding will be used to bind data properties only (like Text etc.) and doesn't make sense to do that for an invisible controls.

    If you are not afraid to use some internals (or as user HighCore would say hacks), then the following helper would help solving your problem (we are using something similar for a years):

    public static class ControlUtils
    {
        static readonly Action CreateControlFunc = (Action)Delegate.CreateDelegate(typeof(Action),
            typeof(Control).GetMethod("CreateControl", BindingFlags.Instance | BindingFlags.NonPublic, null, new[] { typeof(bool) }, null));
        public static void CreateControls(this Control target)
        {
            if (!target.Created)
                CreateControlFunc(target, true);
            else
                for (int i = 0; i < target.Controls.Count; i++)
                    target.Controls[i].CreateControls();
        }
    }
    

    and just put at the beginning of your form load event handler

    this.CreateControls();
    

提交回复
热议问题