現在、シリアル通信からデータを読み取るアプリケーションがあります。アプリケーション全体を通して、このデータを UI に表示する必要があるため、BeginInvoke を使用してテキスト ボックス/ラベル/数値/進行状況バーを更新するメソッドを作成しました。
しかし、これは面倒になり始めています。すべてのコントロールが独自の「Setter」を必要とするため、すでに 20 ほどのメソッドがあり、それらはすべて基本的に同じことを行います。
これを特定のコントロールに一般化する簡単な方法 (例: ラベル用に 1 つ、テキスト ボックス用に 1 つだけ) はわかりますが、UI のデータを更新するために呼び出すことができるメソッド (おそらく拡張) を 1 つだけ持つのが理想的です。 .
これが、いたるところに散らばっている元の方法です。
private void SetCell1Cell2Async(decimal value)
{
if (spinCell1Cell2.InvokeRequired)
{
spinCell1Cell2.BeginInvoke(new EventHandler(delegate
{
spinCell1Cell2.Value = value;
}));
}
else
{
if (spinCell1Cell2.IsDisposed) return; // Do not process if the control has been disposed of
if (spinCell1Cell2.IsHandleCreated)
{
// This handle may not be created when creating this form AFTER data is already flowing
// We could capture this data for future display (i.e. via deferUpdate = true or similar), but it is easier to ignore it
// i.e. Do Nothing
return;
}
spinCell1Cell2.Value = value;
}
}
Text
現在の方法は次のとおりです (これは、プロパティを使用してデータを表示するコントロールで機能します)。
delegate void SetTextAsyncCallback(Control ctrl, string text);
public static void SetTextAsync(this Control invoker, string text)
{
if (invoker.InvokeRequired)
{
invoker.BeginInvoke(new SetTextAsyncCallback(SetTextAsync), invoker, text);
}
else
{
if (invoker.IsDisposed) return; // Do not process if the control has been disposed of
if (!invoker.IsHandleCreated)
{
// This handle may not be created when creating this form AFTER data is already flowing
// We could capture this data for future display (i.e. via deferUpdate = true or similar), but it is easier to ignore it
// i.e. Do Nothing
return;
}
invoker.Text = text;
}
}
ご覧のとおり、このメソッドは、Text
プロパティを使用してそのデータを表示するすべてのもので機能します。
string
理想的には、更新するプロパティを「渡す」ことができ、double
、decimal
、などを取るメソッドを提供できるようにしたいのboolean
ですが、ここからどこへ行くべきか少し迷っています。
どんな助けでも感謝します。