Question

How can I do something like this?

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);
    //...
  }
} 

The ICommand Add_as_Friend is a Button in an ItemsControl.

I need to send my Event to the MainViewModel rather than the person.

Was it helpful?

Solution

You could oberve your ObservableCollection and register the EventHandler to all new items like that (I'm not exactly using your classes structure, you will have to modify it for your project):

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);
            }
        }
    }
}

Edit: underneath is an implementation of the PersonCollection class you want to use. Now you can choose if you want to use one of those implementations. (I would prefer the first)

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);
        }
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top