2

这是我目前正在实施的方式INotifyPropertyChanged-

public class ViewModel : INotifyPropertyChanged
{
    public Person Person1 { get; set; }
    public Person Person2 { get; set; }

    public string Person1Name
    {
        get { return Person1.Name; }
        set 
        { 
            Person1.Name = value;
            RaisePropertyChangedEvent("Person1Name");
        }
    }

    public string Person2Name
    {
        get { return Person2.Name; }
        set 
        { 
            Person2.Name=value;
            RaisePropertyChangedEvent("Person2Name");
        }
    }
}

//This is the Model
public class Person
{
    private string _name;
    public string Name { get; set; }
}

以及我用于此类实现的 XAML -

<Label Text="{Binding Path=Person1Name}"/>
<Label Text="{Binding Path=Person2Name}"/>

我想要做的是每当模型中的任何属性发生更改时对 IRaisePropertyChangedEvent 进行更改,但我不想像在那里那样显式地公开该属性。我只是想公开整个模型,并且每当模型中的属性发生更改时,它应该引发通知事件。但我不希望模型实现 INotifyPropertyChanged,我希望 ViewModel 实现它。所以基本上我正在寻找的是这样的 -

public class ViewModel : INotifyPropertyChanged
{
    public Person Person1
    {
        get { return _person1; }
        set
        {
            _person1 = value;
            RaisePropertyChangedEvent("Person1"); 
            //So, whenever a property within my Person1 changes, raise event for that property.
        }
    }
    public Person Person2
    {
        get { return _person2; }
        set
        {
            _person2 = value;
            RaisePropertyChangedEvent("Person2");
        }
    }
}

XAML:

<Label Text="{Binding Path=Person1.Name}"/>
<Label Text="{Binding Path=Person2.Name}"/>

我该怎么做?如果认为问题不清楚,请发表评论,我会尽力而为。

4

2 回答 2

4

问题是,除非Personimplements ,否则INotifyPropertyChanged您无法跟踪 person 实例中的属性何时更改。

像这样的绑定:

 <Label Text="{Binding Path=Person1.Name}"/>

不改变Person1 实例,而是更改同一实例中的属性。除非该类实现 INPC,否则您将永远不会“看到”该属性已更改,也永远不会引发您的事件。

于 2013-05-31T17:28:54.943 回答
1

您还应该将 Person 对象包装在 ViewModel 中:

public class PersonViewModel : INotifyPropertyChanged
{
   private Person _person;

   public PersonViewModel(Person person)
   {
       _person = person;
   }

   public string Name
   {
       get 
       {
           return _person.Name;
       }
       set
       {
          _person.Name = value;
          RaiseNotifyPropertyChanged("Name");
       }
    }
}

那么您的视图模型类将如下所示:

public class ViewModel : INotifyPropertyChanged
{
    public PersonViewModel Person1
    {
        get { return _person1; }
        set
        {
            _person1 = value;
            RaisePropertyChangedEvent("Person1"); 
            //So, whenever a property within my Person1 changes, raise event for that property.
        }
    }
    public PersonViewModel Person2
    {
        get { return _person2; }
        set
        {
            _person2 = value;
            RaisePropertyChangedEvent("Person2");
        }
    }
}
于 2013-05-31T17:31:56.123 回答