views:

42

answers:

1

I have a readonly .NET property exposed from a managed wrapper which gets the name of the database, let's say the property name is DBName. The DBName may vary depending upon the database connected to the WPF application. This property getter and setter also resides inside the managed .NET wrapper. I am using this(DBName) property in my WPF project.

I want to create a dependency property over this(DBName) .NET property which will be notified whenever this DBName changes. I want to show the DBName on my status bar in the WPF application.

Can I do that?

A: 

Yes

You'll need to implement INotifyPropertyChanged in your wrapper and call PropertyChanged("DBName") each time DBName is changed.

Update

I think this issue can be solved by enforcing a simple rule: always set via the property. If you enforce that, then other programmers won't make the mistake of forgetting to call PropertyChanged("DBName").

public class DBWrapper : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler Propertychanged;

    private string dbName;

    public string DBName
    {
        get { return dbName; }

        private set
        {
            dbName = value;
            if(PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs("DBName"));
            }
        }
    }

    public void SomeMethodThatChangesDBName()
    {
        DBName = "SomethingNew";
    }
}

Using the code this way means that the event gets called every time the DBName is updated.

Matt Ellen
Is there any other way around. Normally I have one method called Connect(string dbname) in my WPF application which calls the connect method of .NET managed wrapper. I can do this in this method to fullfill my requirement but suppose if any new method comes in then I have to make sure that programmer have called the propertychanged ("DBName") or else the code may break.
Ashish Ashu
Well, then make sure that the setter of this property (which could be private) ALWAYS raises the PropertyChanged event. And make sure the only way to update this property is through the setter (never update the backing field directly).
Julian Dominguez