1

我怎么能做这样的事情?

public class person 
{
  public ICommand Add_as_Friend { get; private set; }

  public event EventHandler C1_Friend_Add;

  //....

  Add_as_Friend = new Command(Handle_Add_FR, HandleCan_Add_FR);
  void Handle_Add_FR(object parameter)
  {
    Friend_Add(this, new EventArgs());
  }
}

public class person_Collection : ObservableCollection<person>
{
  //.....
  //???
}

public class MainViewModel : ViewModelBase
{
  public person_Collection person_List{ get; set; }
  public person_Collection person_List2{ get; set; }

  person_Collection.???.item.Friend_Add += new EventHandler(Add);

  void Add(object sender, EventArgs e)
  {
    myPerson = sender as person;
    person_List2.add(myPerson);
    //...
  }
} 

ICommand Add_as_Friend 是ItemsControl 中的一个按钮。

我需要将我的事件发送到 MainViewModel 而不是那个人。

4

1 回答 1

0

您可以观察您的 ObservableCollection 并将 EventHandler 注册到所有类似的新项目(我不完全使用您的类结构,您必须为您的项目修改它):

public class MainViewModel : ViewModelBase
{
    public ObservableCollection<Person> Persons { get; set; }

    public MainViewModel()
    {
        Persons = new ObservableCollection<Person>();
        Persons.CollectionChanged += PersonCollectionChanged;
    }

    private void PersonCollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
    {
        if(e.Action == NotifyCollectionChangedAction.Add)
        {
            foreach(Person person in e.NewItems)
            {
                person.Friend_Add += new EventHandler(Add);
            }
        }
    }
}

编辑:下面是您要使用的 PersonCollection 类的实现。现在您可以选择是否要使用其中一种实现。(我更喜欢第一个)

public class Person
{
    public event EventHandler AddedFriend;
}

public class PersonCollection : ObservableCollection<Person>
{
    public event EventHandler AddedFriend;

    public PersonCollection() : base(new ObservableCollection<Person>())
    {
        base.CollectionChanged += PersonCollectionChanged;
    }

    private void PersonCollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
    {
        if (e.Action == NotifyCollectionChangedAction.Add)
        {
            foreach (Person person in e.NewItems)
            {
                person.AddedFriend += PersonAddedFriend;
            }
        }
    }

    private void PersonAddedFriend(object sender, EventArgs e)
    {
        var addedFriend = AddedFriend;
        if (addedFriend != null)
        {
            addedFriend(sender, e);
        }
    }
}
于 2011-11-24T13:28:11.980 回答