Mapping controls windows forms

1

I'm developing a descktop application in C # The 4.5 framework

I did not think the application could grow and have many fields, so there was a need to do automatic (from / to) mapping of controls to entities ...

Example.

public Pessoa GetPessoaForm()
{
    //Obtém todos os controles de um formulário
    IEnumerable<Control> controles = frm.GetAll();

    Pessoa pessoa = new Pessoa();

    var prop = typeof(pessoa).GetProperties();

    foreach ( Controle control in controles)
    {  
        foreach (var p in prop)
        { 
            If(!p.Name.ToLower().Equals(control.Tag.ToString().ToLower())
                continue;

            If (typeof(control).Equals(typeof(TextBox))
                Control.Text = p.GetValue(prop, null); //erro também
        }
    }
}

In this way I would like to map to the form and vice versa. From the form for entities.

    
asked by anonymous 09.08.2018 / 12:48

1 answer

1

Set the Pessoa class to notify property changes (via the interface INotifyPropertyChanged ), as follows:

class Pessoa : INotifyPropertyChanged
{
    private string nome;
    public string Nome
    {
        get { return nome; }
        set
        {
            nome = value;
            InvokePropertyChanged(new PropertyChangedEventArgs("Nome"));
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;

    public void InvokePropertyChanged(PropertyChangedEventArgs e)
    {
        PropertyChangedEventHandler handler = PropertyChanged;
        if (handler != null) handler(this, e);
    }
}

And then you can use Binding direct:

foreach (Controle control in controles)
{  
    foreach (var p in prop)
    { 
        if(!p.Name.ToLower().Equals(control.Tag.ToString().ToLower())
            continue;

        if (typeof(control).Equals(typeof(TextBox))
            // supondo que a classe Pessoa tem uma propriedade "Nome"
            Control.DataBindings.Add("Text", pessoa, "Nome");
    }
}

In this way the value of the Nome property of the Pessoa class will be directly linked to the text of TextBox .

    
09.08.2018 / 14:43