-1

我有 2 个标签,它们是绑定到我的个人资料概览页面上的对象的数据,让我们假设:

public class Profile
{
    string FirstName { get; set; }
    string LastName {get; set; }
}

我有一个配置文件编辑页面,允许用户更改属性。在此页面的视图模型中,我们传递了 Profile 对象,我们对此进行了克隆,因此如果用户选择不保存,我们可以取消任何更改而不会影响数据绑定标签。

但是,当用户保存更改时,克隆的 Profile 对象被传递回调用视图模型,现在如何使用克隆的对象更新原始 Profile 对象,如下所示:

原始配置文件 = 克隆配置文件;

不起作用,因为数据绑定没有更新,这是预期的行为。如此短的手动更新属性的属性,实现这一点的最佳方法是更新数据绑定控件?

希望这是有道理的。

4

1 回答 1

0

您需要INotifyPropertyChanged在 Model 和 ViewModel 中实现接口,以便 UI 将在运行时更新。

在视图模型中

public class xxxViewModel: INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;


  
    protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }


   

    Profile _originalProfile ;

    Profile originalProfile { 
        
        get
        {
            return _originalProfile ;
        }

        set
        {
            if(_originalProfile !=value)
            {
                _originalProfile = value;
                OnPropertyChanged("originalProfile");
            }
        }
    }




}

在模型

public class Profile: INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    
  
    protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }


    string firstName ;

    string FirstName { 
        
        get
        {
            return firstName ;
        }

        set
        {
            if(firstName !=value)
            {
                firstName = value;
                OnPropertyChanged("FirstName");
            }
        }
    }

    string lastName ;

    string LastName { 
        
        get
        {
            return lastName ;
        }

        set
        {
            if(lastName !=value)
            {
                lastName = value;
                OnPropertyChanged("LastName ");
            }
        }
    }
}

更新

您可以在 Profile 中添加一个方法

// 
void UpdateValue(Profile newValue)
{
  this.FirstName = newValue.FirstName;
  //...
}

现在在 ViewModel 中你只需要像下面这样调用它。

originalProfile.UpdateValue(clonedProfile);
于 2020-07-29T12:09:45.633 回答