Scott
Scott

Reputation: 281

Detect property change

Is there a way in which I can detect if a property value has changed but not when the object is initialized?

public string Foo
{
    set
    {
        // Register property has changed
        // but not on initialization
    }
}

Upvotes: 0

Views: 689

Answers (2)

Karl-Johan Sjögren
Karl-Johan Sjögren

Reputation: 17612

You could do it like this:

public class Bar
{
    private bool _initializing;

    private string _foo;
    public string Foo
    {
        set
        {
            _foo = value;
            if(!_initializing)
                NotifyOnPropertyChange();
        }
    }

    public Bar()
    {
        _initializing = true;
        Foo = "bar";
        _initializing = false;
    }
}

Or just skip the _initializing part and set _foo directly instead of using the setter.

Upvotes: 2

dtb
dtb

Reputation: 217401

If you have a backing field, then you can set the field on initialization and the property thereafter.

private string foo;

public Bar()
{
    foo = "default"; // initialize without calling setter
}

public string Foo
{
    set
    {
        foo = value;
        // setter registers that property has changed
    }
}

Upvotes: 2

Related Questions