0

私のプロジェクトは

手順 1: String 型のリストを作成し、item1、item 2、および item 3 を追加する C# コンソール アプリケーションを作成します。

ステップ 2: タイプ String のコレクションを作成し、これらのアイテムをコピーします。

ステップ 3: List オブジェクトで変更が発生した場合は、Collection オブジェクトに反映する必要があります。

ステップ2まで成功しましたが、私のコードは

class Program
    {
        static void Main(string[] args)
        {
            List<string> newList = new List<string>();
            newList.Add("Item 1");
            newList.Add("Item 2");
            newList.Add("Item 3");

            Collection<string> newColl = new Collection<string>();

            foreach (string item in newList)
            {
                newColl.Add(item);
            }

            Console.WriteLine("The items in the collection are");
            foreach (string item in newColl)
            {
                Console.WriteLine(item);
            }

            Console.ReadKey();
        }
    }

リストで変更が発生した場合、コレクション オブジェクトにもどのように反映されるのでしょうか?

4

1 に答える 1

2

eventの代わりにObservableCollectionList<string>を使用してサブスクライブしてみてくださいCollectionChanged。これは、一般的なアイデアを提供するための非常に単純な実装です。引数のチェックを追加するか、別のタイプの同期を行う必要があります。変更を正確に反映する方法について何も言わなかったからです。Collection

ObservableCollection<string> newList = new ObservableCollection<string>();
newList.Add("Item 1");
newList.Add("Item 2");
newList.Add("Item 3");

Collection<string> newColl = new Collection<string>();


newList.CollectionChanged += (sender, args) => 
        {
            foreach (var newItem in args.NewItems)
            {
                newColl.Add(newItem);
            }
            foreach (var removedItem in args.OldItems)
            {
                newColl.Remove(removedItem);
            }
        };
于 2013-01-16T11:07:42.237 に答える