Question

I have several compass properties one for each side and a direction property. I have the direction bound to a combobox and I have a case statement in the setter of the direction to set the compass points.

The issue I am running into is that the UI isnt refreshing. If I close the form and reopen it, the data has changed to the correct values but the UI wont change dynamically.

What do i need to do?

Was it helpful?

Solution

For the Case you working with WPF, you are looking for the INotifyPropertyChanged interface that allows you to "send" a message with the Property to the UI.

Mostly its in a base that is Called ViewModelBase:

public class ViewModelBase : INotifyPropertyChanged
{
    /// <summary>
    /// Raised when a property on this object has a new value
    /// </summary>
    public event PropertyChangedEventHandler PropertyChanged;

    /// <summary>
    /// Raises this ViewModels PropertyChanged event
    /// </summary>
    /// <param name="propertyName">Name of the property that has a new value</param>
    protected void SendPropertyChanged(string propertyName)
    {
        SendPropertyChanged(new PropertyChangedEventArgs(propertyName));
    }

    /// <summary>
    /// Raises this ViewModels PropertyChanged event
    /// </summary>
    /// <param name="e">Arguments detailing the change</param>
    protected virtual void SendPropertyChanged(PropertyChangedEventArgs e)
    {
        var handler = this.PropertyChanged;
        if (handler != null)
        {
            handler(this, e);
        }
    }

    public void SendPropertyChanged<TProperty>(Expression<Func<TProperty>> property)
    {
        var lambda = (LambdaExpression)property;

        MemberExpression memberExpression;
        if (lambda.Body is UnaryExpression)
        {
            var unaryExpression = (UnaryExpression)lambda.Body;
            memberExpression = (MemberExpression)unaryExpression.Operand;
        }
        else
        {
            memberExpression = (MemberExpression)lambda.Body;
        }
        SendPropertyChanged(memberExpression.Member.Name);
    }

    //.Net 4.5? or 4 and BCL included?
    /// <summary>
    /// Raises this ViewModels PropertyChanged event
    /// </summary>
    /// <param name="propertyName">Name of the property that has a new value</param>
    protected void SendPropertyChanged([CallerMemberName]string propertyName = "")
    {
        SendPropertyChanged(new PropertyChangedEventArgs(propertyName));
    }    
}

Write a SendPropertyChanged(() => Property) or a SendPropertyChanged("Property") into your Setter and the UI will be updated

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top