myesn

myEsn2E9

hi
github

Windows Forms: Using delegates to invoke UI controls in business logic

Background#

Assuming we have a Form that depends on a separate business class, and we want to control UI controls inside the Form from the business class, such as updating a progress bar, we need to use delegate.

A delegate is a reference to a method that wraps the method, and the reference is passed as a parameter to other methods. After other methods receive the reference, they can execute it as if they were calling the method.

Here, for simplicity, let's assume that we need to specify a popup for the content in the business.

Define Delegate#

Create a Global.cs file and define the delegate and the required parameters inside it:

namespace WindowsFormsApp1
{
    public class Global
    {
        // Define a delegate with parameters
        public delegate void CallBack(Data data);
    }

    public class Data
    {
        public string Name { get; set; }
    }
}

BLL#

Then pass the delegate as a parameter to the business method and execute the delegate:

using System.Threading.Tasks;
using static WindowsFormsApp1.Global;

namespace WindowsFormsApp1
{
    public class BLL
    {
        public void SayHi(CallBack callback) =>
            Task.Run(() => { callback(new Data { Name = "bob" }); });
    }
}

Form#

Then, in the Form, initialize the delegate and execute the business function:

using System.Windows.Forms;
using static WindowsFormsApp1.Global;

namespace WindowsFormsApp1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();

            // Instantiate the delegate and pass the delegated function
            var callback = new CallBack(AnyMethod);
            
            // Specify the business logic
            new BLL().SayHi(callback);
        }

        private void AnyMethod(Data data) 
            => MessageBox.Show($"Hi, {data.Name}");        
    }
}

That's it.

Optimization#

C# provides two pre-defined delegates:

  • Action: Takes parameters and has no return value
  • Func: Takes parameters and has a return value

This way, we don't have to define the delegate ourselves, so let's modify the program.

Global#

Delete the Global class.

BLL#

public void SayHi(Action<Data> callback)

Form#

new BLL().SayHi(new Action<Data>(AnyMethod));
Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.