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 に答える