开发者

Exposing property to databinding in WPF

This is my scenario. I have internal class with a standard int property.

public class Session : INotifyPropertyChanged {
    public event PropertyChangedEventHandler PropertyChanged;

    private ushort _Level;
    public ushort Level
    {
        get { return _Level;开发者_JAVA百科 }
    }

    private void OnPropertyChanged(string name)
    {
        if (PropertyChanged != null)
            PropertyChanged(this, new PropertyChangedEventArgs(name));
    }

    // a timer code here updates the _Level property every 60 seconds
    // and calls OnPropertyChange("Level");
}

In my UI window, I have a label that binds to the Session instance and displays the Level value.

 <TextBlock Name="LevelTextBlock" Text="{Binding SessionInstance.Level, StringFormat='0%'}" />

And the window constructor has this code:

 public MyWindow()
    {
        SessionInstance = new Session();

        this.InitializeComponent();
    }

    public Session SessionInstance { get; set; }

However, as you can guess, when I update the value of _Level, the UI doesn't update the textblock. Adding DependancyProperty inside the Session class is unacceptable. I could do this on the window, but then I still need notifier that would check the value back to the Session instance. I was wondering if there's elegant way of doing this. I can't think of anything, other than running another timer in the window that would check and refresh the textblock value. Any thoughts?


Implement INotifyPropertyChanged. There is even an tool which can do that automatically for all of your properties (or only ones marked by attribute, it is fairly configurable).

DependencyProperty is overkill if you don't need any of its other features (value inheritance, binding FROM the property etc.), it is best used for control properties, not model properties.

EDIT:

Correctly implemented it looks like this:

private string familyName;
public string FamilyName
{
    get { return familyName; }
    set 
    {
        if (value != familyName)
        {
            familyName = value;
            OnPropertyChanged("FamilyName");
        }
    }
}


Are you calling OnPropertyChanged from the property setter? This is really where it belongs.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜