【问题标题】:How to set ErrorProvider Icon left for all Controls programmatically如何以编程方式为所有控件设置 ErrorProvider 图标
【发布时间】:2010-05-19 10:29:25
【问题描述】:

我们使用派生的表单类,我们的软件有一个基本表单类。

在派生表单上,我们广泛使用 DataBinding 来处理我们的 BusinessObjects,所有这些都实现了 IDataErrorInfo,使用 ErrorProviders 在 GUI 的错误输入上抛出自定义错误消息。

我现在寻找一种方法来在基表单类中实现一个函数,以获取表单上的所有 ErrorProvider-Components,并将表单上每个控件的 IconAlignment 设置为左​​(因为右是间距问题) .

欢迎任何提示...

设置图标对齐的代码:

private void SetErrorProviderIconAlignment(ErrorProvider errorProvider, Control control)
{
    errorProvider.SetIconAlignment(control, ErrorIconAlignment.MiddleLeft);

    foreach (Control subControl in control.Controls)
    {
        SetErrorProviderIcon(errorProvider, subControl);
    }
}

【问题讨论】:

    标签: c# winforms errorprovider


    【解决方案1】:

    我们使用继承的 ErrorProvider 组件代替它强制设置/返回 IconAlignment 扩展属性的默认值。

    例如

    [ToolboxBitmap(typeof(ErrorProvider))]
    [ProvideProperty("IconAlignment", typeof(Control))]
    public class MyErrorProvider : ErrorProvider
    {
        #region Base functionality overrides
    
        // We need to have a default that is explicitly different to 
        // what we actually want so that the designer generates calls
        // to our SetIconAlignment method so that we can then change
        // the base value. If the base class made the GetIconAlignment
        // method virtual we wouldn't have to waste our time.
        [DefaultValue(ErrorIconAlignment.MiddleRight)]
        public new ErrorIconAlignment GetIconAlignment(Control control)
        {
            return ErrorIconAlignment.MiddleLeft;
        }
    
        public new void SetIconAlignment(Control control, ErrorIconAlignment value)
        {
            base.SetIconAlignment(control, ErrorIconAlignment.MiddleLeft);
        }
    
        #endregion
    }
    

    然后您可以轻松地搜索/替换new ErrorProvider() 并替换为new MyErrorProvider()

    我记不清了,但您可能会发现您可能需要打开表单的设计器才能重新序列化传递给form.designer.cs 文件中SetIconAlignment 的值...

    【讨论】:

    • @BeowulfOF - 我不确定你的意思?常规 ErrorProvider 通过在绑定对象上实现 IDataErrorInfo 来支持数据绑定属性的验证。您需要将 ErrorProvider 的 DataSource 属性设置为控件绑定中使用的相同 BindingSource。
    • 做到了,但子类错误提供者不使用填充和对齐..
    • @BeowulfOF - 根据答案,您会发现对齐/填充通常在 .designer.cs 文件中设置,因此您必须打开设计器或在其中搜索您的 SetIconAlignment 语句删除它们或打开 Winforms 设计器,希望它们将重置为我们在新子类中重新定义的默认值。
    • 还建议搜索任何出现的“ErrorProvider”并决定是否必须更改它。 (例如,一些演员表,如果有的话,可能无法按预期工作)。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-03
    • 1970-01-01
    相关资源
    最近更新 更多