如何通过编程为所有控件设置ErrorProvider图标在左侧

4
我们使用派生的表单类,在我们的软件中有一个基本的表单类。
在派生的表单上,我们广泛使用DataBinding来处理我们的BusinessObjects,所有实现IDataErrorInfo的对象都会在GUI上通过ErrorProviders抛出自定义错误信息以应对错误输入。
我现在正在寻找一种方法,在基本表单类中实现一个函数,以获取表单中所有的ErrorProvider组件,并将表单上每个控件的IconAlignment设置为左对齐(因为右对齐会导致间距问题)。
欢迎提供建议...
设置IconAlignment的代码:
private void SetErrorProviderIconAlignment(ErrorProvider errorProvider, Control control)
{
    errorProvider.SetIconAlignment(control, ErrorIconAlignment.MiddleLeft);

    foreach (Control subControl in control.Controls)
    {
        SetErrorProviderIcon(errorProvider, subControl);
    }
}
1个回答

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()替换。

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


@BeowulfOF - 不太确定你的意思?常规的ErrorProvider通过在绑定对象上实现IDataErrorInfo来支持数据绑定属性的验证。您需要将ErrorProvider的DataSource属性设置为控件绑定中使用的相同BindingSource。 - Reddog
已经完成了这个任务,但是从子类化的错误提供程序中没有使用填充和对齐。 - Oliver Friedrich
根据答案,您会发现对齐/填充通常在.designer.cs文件中设置,因此您必须打开设计器或在其中搜索SetIconAlignment语句以删除它们,否则打开Winforms设计器,希望它们将被重置为我们在新子类中重新定义的默认值。 - Reddog
建议还要搜索任何出现的“ErrorProvider”,并决定是否需要更改(例如,某些强制转换可能无法按预期工作)。 - ilias iliadis

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接