从 dll 更新 C# 桌面应用程序 GUI

Updating a C# desktop application GUI from a dll

我正在编写一个 C# 桌面应用程序,它利用一个 dll(我编写的)从数据库中检索数据。

根据用户需要的数据,dll 具有多种功能。我想更新我的应用程序 UI 上的标签,因为数据库功能已在 dll 中完成。

我的代码布局如下:

申请:

private void getData(object sender, EventArgs e)
{
     dll.DoDatabaseFunctions();
}

DLL:

public static DataTable getThisStuff
{
     //connections to SQL DB and runs command
     //HERE is where I would like to send something back to the application to update the label
}

public static DataTable getThatStuff
{
     //connections to SQL DB and runs command
     //HERE is where I would like to send something back to the application to update the label
}

如有任何想法,我们将不胜感激!

在你的 dll class 中创建一个 event,你可以在你的 gui 中订阅。

在您的 dll 中声明事件:

public event Action DataReady;

需要时在 dll 中引发事件:

DataReady?.Invoke();

var dataReady = DataReady;
if (dataReady  != null) 
    dataReady();

在 gui 中订阅事件:

dll.DataReady += OnDataReady;

引发事件时在 gui 中更新标签:

public void OnDataReady()
{
     label.Text = "Whatever";
}

如果您需要参数,可以为您的活动使用 Action<T1,..,Tn>。例如:

public event Action<string> DataReady;
DataReady?.Invoke("data");

dll.DataReady += OnDataReady;
public void OnDataReady(string arg1)
{
   label.Text = arg1;
}

最后,取消订阅不再需要的活动:

dll.DataReady -= OnDataReady;

您可以使用事件。在你的 dll 中定义一个事件 class,你不能真正使用静态,因为你需要一个实例(静态事件不是一个好主意)。

像这样:

private void getData(object sender, EventArgs e)
{
     var dllInstance = new Dll();
     dll.Updated += dllUpdateReceived;
     dllInstance.DoDatabaseFunctions();
}

private void dllUpdateReceived(object sender, DllUpateEventArgs e)
{
    var updateDescription = e.UpdateDescription;
    // TODO: Update a label with the updates

}

以及dll项目中必要的东西:

public class DllUpdateEventArgs: EventArgs {
    public string UpdateDescription { get; set; }
}

public class Dll {
    public event EventHandler<DllUpdateEventArgs> Updated;
    private void OnUpdated(string updateDescription) {
        var updated = Updated;
        if (updated != null) {
            updated(this, new DllUpdateEventArgs { UpdateDescription = updateDescription });
        }
    }

    public void DoDatabaseFunctions() {
        // Do things
        OnUpdated("Step 1 done");
        // Do more things
        OnUpdated("Step 2 done");
        // Do even more things
        OnUpdated("Step 3 done");
    }
}