Ways to update view-type elements

5

This is a doubt that I've always had, I've always stepped out of ways a bit sloppy and that's why I've been encouraged to ask this.

  

What are different ways to update view elements?

Let's say we have a form, basic, Form1 , with its Form1.cs and part of this we have a class called Vista or Clase . As in this diagram below.

The idea is to collect different forms and examples to update these elements of type view, in this case a Label cuadno press a Button , so that they can be applied to another type of elements.

Class Form1 :

public partial class Form1 : Form {
    public Form1() {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e) {

    }
}

Example class:

class Class1 {



    // Metodo para actualizar la label 
    // Ejemplo: 

     Label devolverLabel() {
        var label = new Label();
        label.Text = "Hola mundo";

        return label;
    }


}
    
asked by Aritzbn 25.05.2018 в 09:34
source

2 answers

1

Something I usually use is the following.

1- I create a clase with propiedades replicated to which I will need to update in this case it is only a label .

class ReplicaVista {

    public Label label { get; set; }

    public ReplicaVista() {
        this.label = new Label();
        this.label.Text = ""; //Inicializo la label para evitar valores null
    }


}

2- I create an object in the class from which I will update the elements.

//Creamos objeto
static ReplicaVista formulario = new ReplicaVista();

void ActualizarLabel() {

    //Lo actualizamos
    formulario.label.Text = "Hola mundo!";
}

3- Using a timer I will update the properties in Form1 .

    private void timer1_Tick(object sender, EventArgs e) {
        label1.Text = Class1.formulario.label.Text;

    }
  

This I usually use when I work with Threads , Tasks ... to have a kind of Node where I compile the classes, without having to fill the class with Form1 of method calls.

    
answered by 25.05.2018 в 09:44
1

You can use the Redux pattern that is used in web pages made with React, with that you manage the status of your application globally, and it is thread-safe since the state is immutable.

Examples of implementations of the Redux pattern in C # have several:

You have Redux.Net: link

O Reducto: link

Here is an example with Reducto (which is the one I used):

First define a structure where the data you want to have globally will be:

public struct AppState
{
    public string ValorLabel; // este sería el texto que quieres poner en los labels en todos los formularios
}

Then you create an "action" for each data you have declared, you can only modify the status by means of actions, not directly:

// esta acción cambia el valor de la label a otro texto
public struct CambiaLabel { 
    public string NuevoValor { get; set;}
}

// esta acción borra el texto de la label
public struct BorraLabel {
    // no le agregamos ninguna propiedad porque simplemente borra el texto
}

Then you create the reducers, the reducers are those that modify or alter the state:

var reducer = new SimpleReducer<AppState>()
    .When<CambiaLabel>((state, action) => {
        // la store nos pasa el estado actual (en state) y la acción que se va a realizar (en action)
        state.ValorLabel = action.NuevoValor; // modificamos el estado con el valor que viene en la action
        return state; // regresamos el nuevo estado
    })
    .When<BorraLabel>((state, action) => {
        // de nuevo la store nos pasa el estado actual (en state) y la acción a realizar, pero en este caso la acción no trae ningún parámetro
        state.ValorLabel = string.Empty; // modificamos el estado
        return state; // regresamos el estado
    });

And finally you create the store object, which is the one that contains the status of your application:

var store = new Store<AppState>(reducer); // le pasamos el reducer que creamos anteriormente

You can do a singleton without problem, just declare it read only:

public static class Store
{
     readonly Store<AppState> store;
     static Store()
     {
           var reducer = new SimpleReducer<AppState>()
              .When<CambiaLabel>((state, action) => {
                  state.ValorLabel = action.NuevoValor;
                  return state;
               });
           store = new Store<AppState>(reducer);
     }

     public static Store<AppState> Instance => store;
 }

And ready, to update the status you just have to write:

private void button1_Click(object sender, EventArgs e) 
{
     Store.Instance.Dispatch(new CambiaLabel { NuevoValor = "Hola mundo" }); 
}

You can do it from anywhere in the code.

And to know when the status changes (and so you update in all views):

// Subscribe se va a ejecutar cada vez que en alguna parte se modifica el estado por medio de una acción
Store.Instance.Subscribe(state =  {
        // en state nos llega el estado ya actualizado
        // y puedes usarlo para lo que quieras
        label.Text = state.ValorLabel;
    });

For example, if you have several forms and want to have a label that says the same thing in all of them, because you use the code above in each one, and its content will be synchronized.

The idea is that you do not fall into bad habits falling into the temptation of using a mutable Singleton, which is not recommended, an immutable singleton is better.

    
answered by 30.05.2018 в 04:08