如何在 TabPage 标题旁边显示 ErrorProvider 错误图标?

2023-12-19

Edit:这不是重复的TabControl C# 中的图标 - 如何实现? https://stackoverflow.com/questions/3663603/icons-in-tabcontrol-c-sharp-how。问题是关于向选项卡页面添加图标。这里是关于如何将错误提供程序错误图标位置更改为标题内部而不是选项卡页面本身的右侧。此外,错误提供程序错误图标具有以下功能:当您将鼠标悬停在其上时,您会看到错误文本,而如果您只是将图标添加到标题中,则不会看到该文本。


我有一个表格TabControl。该表格还有一个ErrorProvider。当我尝试使用以下代码时:

errorProvider1.SetError(tabPage1, "error");

The error icon is shown to the right of the tab page, and it is cut-off by the tab control itself: 1]

我希望图标显示在选项卡页标题旁边。像这样的东西(用 Photoshop 制作):

我不知道从哪里开始,也不知道如何解决这个问题。

Edit:我有一个类负责向控件添加错误,并使用错误提供程序显示它们。该类用于TextBoxes, NumericUpDown等。我也想用它来TabPages。问题是,当我将它用于选项卡页面时,我得到了上面显示的结果。使用以下方法将错误图标添加到标题的技巧ImageList然后添加工具提示不好,因为它是特定于选项卡页的,并且我无法在我的类中实现它,而该类对所有控件都是通用的。所以我真的需要更改标签页的设置,以便当我使用errorProvider.SetError(...)它显示在标题中。


ErrorProvider显示错误图标TabPage在标签页的客户区。 通过玩IconAlignment or IconPadding,您可以显示错误图标TabControl在其中一个标签页的标题上,但它是整个标签页的错误图标TabControl.

在实际应用程序中,每个选项卡页都可以包含无效的控件,并且您可能希望在选项卡页上不显示选项卡控件的验证图标。

我的建议是通过设置使用标签页图标ImageList包含错误图标作为图像列表TabControl并通过设置ImageIndex of the TabPage,显示或隐藏图像图标。这样您就可以为每个需要它的选项卡页显示错误图标:

Example

要设置示例,请按照下列步骤操作:

  1. 创建一个Form.
  2. Drop a TabControl, an ErrorProvider and an ImageList on the Form.
  3. Set ImageList的财产tabControl1 to imageList1.
  4. 丢两个TextBox on tabPage1.
  5. 我假设,仅举例来说,您将使用以下方法验证这两个文本框控件Validating事件。关键点就在这里。当您验证任何控件时,请检查它是否托管在TabPage,检查所有子项的有效性TabPage并据此设置错误图标:

    protected override void OnLoad(EventArgs e)
    {
        base.OnLoad(e);
        this.AutoValidate = AutoValidate.EnableAllowFocusChange;
        imageList1.ColorDepth = ColorDepth.Depth32Bit;
        imageList1.Images.Add(errorProvider1.Icon);
        tabControl1.ImageList = imageList1;
        textBox1.Validating += textBox_Validating;
        textBox2.Validating += textBox_Validating;
    }
    private void textBox_Validating(object sender, CancelEventArgs e)
    {
        var textBox = (TextBox)sender;
        if (string.IsNullOrEmpty(textBox.Text))
        {
            this.errorProvider1.SetError(textBox, "Value is required.");
            e.Cancel = true;
        }
        else
            this.errorProvider1.SetError(textBox, null);
        var tabPage = textBox.Parent as TabPage;
        if (tabPage != null)
            ValidateTabPage(tabPage);
    }
    void ValidateTabPage(TabPage tabPage)
    {
        var tabIsValid = tabPage.Controls.Cast<Control>()
            .All(x => string.IsNullOrEmpty(errorProvider1.GetError(x)));
        if (tabIsValid)
            tabPage.ImageIndex = -1;
        else
            tabPage.ImageIndex = 0;
    }
    
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在 TabPage 标题旁边显示 ErrorProvider 错误图标? 的相关文章

随机推荐