Datacontext值更改时刷新文本框

时间:2013-08-05 15:27:25

标签: c# user-interface datacontext

我有几个罗盘属性,每侧一个方向属性。我有一个方向绑定到一个组合框,我在设置罗盘点的方向设置器中有一个case语句。

我遇到的问题是UI不令人耳目一新。如果我关闭表单并重新打开它,数据已更改为正确的值,但UI不会动态更改。

我需要做什么?

1 个答案:

答案 0 :(得分:2)

对于使用WPF的案例,您正在寻找允许您将带有属性的消息“发送”到UI的INotifyPropertyChanged界面。

主要是在一个名为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));
    }    
}

SendPropertyChanged(() => Property)SendPropertyChanged("Property")写入您的Setter,用户界面将会更新