Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delegate specifics

Tags:

c#

delegates

xna

I have problem with a delegate in a class on a project that I'm working on. The class is a GUI Component that accepts both a label and a value. The idea here is that a user can specify a label, and then link in a value from anywhere (more specifically, that value's ToString Method) so that every time that value is updated, the GUI Component is as well. This is the basics of how it is set up:

public delegate string GUIValue();

public class GUIComponent
{
    GUIValue value = null;    // The value linked in
    string label = "";        // The label for the value
    string text = "";         // The label and value appended together

    public GUIComponent(string Text, GUIValue Value)
    {
        this.text = Text;
        this.value += Value;
    }

    public void Update()
    {
        this.text = this.label + this.value();
    }
}

And then I call it like this

GUIComponent component = new GUIComponent("Label: ",
                                new GUIValue(this.attribute.ToString));

The Code compiles correctly, and the component does display, and displays the initial value for the attribute given to it, however, it does not update whenever the attribute value is changed.

My question is whether or not I even have this set up right in the first place, and if so why it would not be working. My initial thought is that it only accepts the first value return by the ToString method, since it doesn't take any arguments, but can anyone verify that?

like image 612
shmeeps Avatar asked Aug 01 '26 19:08

shmeeps


1 Answers

This code:

new GUIValue(this.attribute.ToString)

will not cause the method to be called every time the attribute changes. You'd have to store the delegate and call it each time someone changes "attribute". Something like:

private event GUIValue attributeChanged = () => this.attribute.ToString();

private String attribute;

// This is a property that sets the value of attribute
public String Attribute { get { return attribute; } set { attribute = value; attributeChanged(); } }

// Now you can initialize the component using:
// GUIComponent component = new GUIComponent("Label: ", this.attributeChanged);
like image 93
Chris Shain Avatar answered Aug 03 '26 10:08

Chris Shain



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!