MVVM - 如何使格式化的属性保持最新?

epa*_*aps 4 c# mvvm windows-phone windows-phone-8

我正在使用一个使用MVVM的Windows Phone应用程序,但我正在努力实现MVVM,以便需要从模型类格式化以在视图中显示的属性.

假设我有一个简单的模型类叫做Person.

public class Person {

   public string Name { get; set; }
   public DateTime Birthday { get; set; }

}
Run Code Online (Sandbox Code Playgroud)

有名单Person,是根据本地保存的文件加载的对象,我想显示一个列表页面上的人员名单,然后让一个人的用户水龙头导航到详细信息页面,那里有更多这方面的细节人.

在列表页面上,我想将此人的生日显示为"生日:2/22/1980"(其中"2/22/1980"是该人的格式Birthday)

在详细信息页面上,我想以不同的格式显示此人的生日:"Eric的生日是2/22/1980"(其中"Eric"是此人Name,"2/22/1980"是该人的格式Birthday).

通常,我会创建一个Birthday正确格式化的视图模型:

public class PersonViewModel {

   private Person person;

   public PersonViewModel(Person person) {
      this.person = person;
   }

   public string BirthdayForList {
      get {
         return "Birthday: " + person.Birthday.ToString("ddd", CultureInfo.CurrentCulture);
      }
   }

   public string BirthdayForDetails {
      get {
         return person.Name + "'s birthday is " + person.Birthday.ToString("ddd", CultureInfo.CurrentCulture);
      }
   }

}
Run Code Online (Sandbox Code Playgroud)

为了在UI中显示这些值,我将创建这些视图模型对象的集合(并将它们绑定到视图):

ObservableCollection<PersonViewModel> Items
Run Code Online (Sandbox Code Playgroud)

现在,我做了什么,当一个人的生日(某处细节页)更新,并确保Items已经更新,最多最新BirthdayForListBirthdayForDetails性能,而在同一时间保存Person在本地?

我想保持一切简单,每次需要更新值时,不必手动更新保存的Person对象列表和PersonViewModel对象列表.

做这个的最好方式是什么?我应该使用ObservableCollection一些PersonViewModel物体吗?另外,我在本网站的几个地方读过模型类不应该实现的内容NotifyPropertyChanged.

(注:我已经简化了这个问题,这个问题你应该假设有,我需要格式化许多其他方式.Birthday从需要在不同的页面不同格式的模型类在整个应用程序属性以及其他属性. )

Sta*_*eff 5

为什么不简单地在xaml中完成整个事情并且不使用"计算属性"?

<TextBlock>
    <TextBlock.Text>
        <MultiBinding StringFormat="{}{0}'s birthday is {1:ddd}">
            <Binding Path="Person.Name">
            <Binding Path="Person.BirthDay">
        </MultiBinding>
    </TextBlock.Text>
</TextBlock>
Run Code Online (Sandbox Code Playgroud)

然后,您需要做的就是INotifyPropertyChanged在Person类中实现并在setter中引发事件.

编辑:我也建议使用像一个框架MVVM光,所以你可以使用ViewModelObservableObject基类为对象,简单地能够使用其实施的INotifyPropertyChanged

public string FirstName
{
    get { return _firstName; }
    set
    {
        _firstName = value;
        RaisePropertyChanged(() => FirstName);
    }
}
private string _firstName;
Run Code Online (Sandbox Code Playgroud)