简体   繁体   中英

How can I execute code when value of a variable changes in C#?

I want to toggle a button's visibility in when value of a particular variable changes. Is there a way to attach some kind of delegate to a variable which executes automatically when value changes?

No, you can't do things like overloading assignment operator in C#. The best you could do is to change the variable to a property and call a method or delegate or raise an event in its setter.

private string field;
public string Field {
   get { return field; }
   set { 
       if (field != value) {
           field = value;
           Notify();
       } 
   }
}

This is done by many frameworks (like WPF DependencyProperty system) to track property changes.

You can also use Data Binding: in WPF , in Windows Forms . This allows you to change the state of GUI depending on objects' properties and vice versa .

There is no way to do that. Variables are basically just places in memory that your application writes to.

Use a property instead:

string myVariable;
public string MyVariable
{
    get
    {
        return myVariable;
    }
    set
    {
        myVariable = value;
        MyVariableHasBeenChanged();
    }
}

private void MyVariableHasBeenChanged()
{

}

You either have a reference to the GUI in your model (where the variable is) and directly perform the GUI change in the setter method, or you make your GUI observe your model via an observer, and have the observable model fire events to the observers in the setters. The former will lead to spaghetti code eventually, as you add more and more direct links between model and view, and thus should only be used for in-house tools and simple programs.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM