开发者

Using dependency property in WPF

开发者 https://www.devze.com 2023-01-20 08:56 出处:网络
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 DBNa开发者_运维百科me may vary depending upon the databa

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 DBNa开发者_运维百科me 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?


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号