【问题标题】:How to set properties of new TabPage pages at TabControl?如何在 TabControl 中设置新 TabPage 页面的属性?
【发布时间】:2015-09-01 08:30:32
【问题描述】:

当新的 TabControl 被放置在设计器中时,它带有两个默认的 TabPage 页面:

我可以轻松地继承和修改 TabControl 本身,但是
如何拦截标签页的创建并设置它们的属性?

  • 例如,对于每个 TabPage,我默认需要 UseVisualStyleBackColor = false

(C# 或 VB - 随便你。)

【问题讨论】:

    标签: c# .net vb.net winforms tabcontrol


    【解决方案1】:

    您可以处理ControlAdded 事件并测试添加的控件并相应地对其进行处理:

      Private Sub TabControl1_ControlAdded(sender As Object, e As ControlEventArgs) Handles TabControl1.ControlAdded
        Debug.WriteLine("Something added: " & e.Control.Name & " " & e.Control.GetType().ToString)
    
       If TypeOf e.Control Is TabPage Then
          Dim tp As TabPage = CType(e.Control, TabPage)
          tp.UseVisualStyleBackColor = False
        End If
      End Sub
    

    【讨论】:

    • 谢谢@Dennis。我已经更新了我的答案以获得更强大的测试
    【解决方案2】:

    继承 TabControl 并覆盖 OnControlAdded 方法。

    class MyTabControl : TabControl
    {
        protected override void OnControlAdded(ControlEventArgs e)
        {
            base.OnControlAdded(e);
    
            var page = e.Control as TabPage;
            if (page != null)
            {
                page.UseVisualStyleBackColor = false;
                page.BackColor = Color.Red;
    
            }
        }
    }
    

    这样,如果您使用代码或使用设计器添加 TabPage,您的设置将被应用。

    在这种情况下,继承比事件处理效果更好,因为不需要在项目中的每个表单上处理 ControlAdded 事件。

    【讨论】:

    • 也很有帮助,谢谢。 @joehanna 是第一个提出关键想法的人,所以我会奖励他的答案。
    • 谢谢你,你是对的,当他发布他的好答案时,我正在测试解决方案。无论如何,考虑继承也会对其他人有所帮助:)
    • 是的,当然。感谢您的回答,+1,它很棒并且代码简洁。 (检查我的最终实施答案。)
    【解决方案3】:

    为了方便其他人,我分享一下我最终实现的内容。

    致谢 前往 @joehanna 获取创意,@Reza Aghaei 获取简洁代码。所以我的解决方案是基于他们的贡献:

    Public Class TabBasedMultipage : Inherits TabControl
    
        Protected Overrides Sub OnControlAdded(e As ControlEventArgs)
    
            MyBase.OnControlAdded(e)
    
            Dim tabPage As TabPage = TryCast(e.Control, TabPage)
            If tabPage IsNot Nothing Then
                tabPage.UseVisualStyleBackColor = False
            End If
    
        End Sub
    
    End Class
    

    【讨论】:

    • 谢谢您,感谢您快速准确的回答和您的好意:)
    猜你喜欢
    • 2021-01-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-08
    • 1970-01-01
    • 1970-01-01
    • 2010-10-07
    • 2021-06-18
    相关资源
    最近更新 更多