Bind a label to a “variable”

后端 未结 4 1056
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-05 05:02

Say I have a global variable INT named X. Since X is global, we can assume that anything can modify its value so it is being changed everytime.

Say I have a Label co

4条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-05 05:16

    For a multi-threaded program (so almost every windows forms program) iCe's answer is not a good one, because it won't let you change the label anyway (you will get some cross-threading error). The simplest way to fix the problem is creating property in setter:

    private string _labelText;
    public string labelText
    {
        get { return _labelText; }
        set
        {
            _labelText = value;
            updateLabelText(_labelText); //setting label to value
       }
    }
    

    where updateLabelText(string) is thread safe:

    delegate void updateLabelTextDelegate(string newText);
    private void updateLabelText(string newText)
    {
         if (label1.InvokeRequired)
         {
              // this is worker thread
              updateLabelTextDelegate del = new updateLabelTextDelegate(updateLabelText);
              label1.Invoke(del, new object[] { newText });
         }
         else
         {
              // this is UI thread
              label1.Text = newText;
         }
    }
    

提交回复
热议问题