数据绑定是否对隐形控制起作用?

Ste*_*eve 8 .net c# winforms

这是winforms的.net问题,而不是asp.net.

我有一个带有几个标签的窗体.我在加载表单时设置所有控件的数据绑定.但我注意到第二个选项卡上的控件的数据绑定不起作用.这些绑定仅在加载表单和选择第二个选项卡时起作用.这给我带来了怀疑:数据绑定仅在绑定控件可见时才起作用.

任何人都可以告诉我这是否属实?测试这个并不难,但我想知道一些确认.

谢谢

Mic*_*tta 10

你是对的.在控件可见之前,不会更新数据绑定控件.

我目前唯一可以找到的参考是这个MSDN线程.


Has*_*ell 5

您的问题与 TabControl 的行为有关。请参阅Microsoft 错误报告。我发布了一个解决该问题的方法,该方法将 TabControl 子类化,并在创建控件或创建句柄时“初始化”所有选项卡页。下面是解决方法的代码。

public partial class TabControl : System.Windows.Forms.TabControl
{
    protected override void OnHandleCreated(EventArgs e_)
    {
        base.OnHandleCreated(e_);
        foreach (System.Windows.Forms.TabPage tabPage in TabPages)
        {
            InitializeTabPage(tabPage, true, Created);
        }
    }

    protected override void OnControlAdded(ControlEventArgs e_)
    {
        base.OnControlAdded(e_);
        System.Windows.Forms.TabPage page = e_.Control as System.Windows.Forms.TabPage;
        if ((page != null) && (page.Parent == this) && (IsHandleCreated || Created))
        {
            InitializeTabPage(page, IsHandleCreated, Created);
        }
    }

    protected override void OnCreateControl()
    {
        base.OnCreateControl();
        foreach (System.Windows.Forms.TabPage tabPage in TabPages)
        {
            InitializeTabPage(tabPage, IsHandleCreated, true);
        }
    }

    //PRB: Exception thrown during Windows Forms data binding if bound control is on a tab page with uncreated handle
    //FIX: Make sure all tab pages are created when the tabcontrol is created.
    //https://connect.microsoft.com/VisualStudio/feedback/details/351177
    private void InitializeTabPage(System.Windows.Forms.TabPage page_, bool createHandle_, bool createControl_)
    {
        if (!createControl_ && !createHandle_)
        {
            return;
        }
        if (createHandle_ && !page_.IsHandleCreated)
        {
            IntPtr handle = page_.Handle;
        }
        if (!page_.Created && createControl_)
        {
            return;
        }
        bool visible = page_.Visible;
        if (!visible)
        {
            page_.Visible = true;
        }
        page_.CreateControl();
        if (!visible)
        {
            page_.Visible = false;
        }
    }
} 
Run Code Online (Sandbox Code Playgroud)