我正在制作一个扩展方法库,以便在Windows窗体应用程序中使用。我打算创建的一种方法将使在输入控件上设置错误状态更加容易,例如

public static void SetError(this System.Windows.Forms.TextBox textBox, string errorMessage)
{
    if (string.IsNullOrEmpty(errorMessage))
    {
        //reset control state
        textBox.BackColor = System.Drawing.SystemColors.WindowText;
    }
    else
    {
        //set background colour to a nice shade of red
        textBox.BackColor = System.Drawing.Color.MistyRose;
    }

    //try to locate an ErrorProvider on the control's containing form.
    var errorProvider = LocateErrorProvider(textBox);

    if (errorProvider != null)
    {
        //set error message on error provider (or clear it)
        errorProvider.SetError(textBox, errorMessage);
    }
}


我正在尝试找出LocateErrorProvider方法。我想做的是检查我的表单上是否存在ErrorProvider,然后仅在确实存在时使用它。

ErrorProvider是一个Component而不是Control,因此我无法通过form.Controls属性来获取它。我试图将父窗体转换为各种对象,但无济于事。

更新:我已经设法通过使用以下代码的反射来到达ErrorProvider:

private static System.Windows.Forms.ErrorProvider GetErrorProvider(System.Windows.Forms.Control control)
{
    //get the containing form of the control
    var form = control.GetContainerControl();

    //use reflection to get to "components" field
    var componentField = form.GetType().GetField("components", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);

    if (componentField != null)
    {
        //get the component collection from field
        var components = componentField.GetValue(form);

        //locate the ErrorProvider within the collection
        return (components as System.ComponentModel.IContainer).Components.OfType<System.Windows.Forms.ErrorProvider>().FirstOrDefault();
    }
    else
    {
        return null;
    }
}


就个人而言,我不太喜欢使用硬编码的字段名称来访问该字段。但是在这种情况下,它似乎工作正常。是否有人有更好的方法来达到相同的结果?

最佳答案

到目前为止,这似乎解决了我的问题:

private static System.Windows.Forms.ErrorProvider GetErrorProvider(System.Windows.Forms.Control control)
{
    //get the containing form of the control
    var form = control.GetContainerControl();

    //use reflection to get to "components" field
    var componentField = form.GetType().GetField("components", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);

    if (componentField != null)
    {
        //get the component collection from field
        var components = componentField.GetValue(form);

        //locate the ErrorProvider within the collection
        return (components as System.ComponentModel.IContainer).Components.OfType<System.Windows.Forms.ErrorProvider>().FirstOrDefault();
    }
    else
    {
        return null;
    }
}


感谢Hans&Cody的出色创意。

10-05 23:46