Click here to Skip to main content
15,891,938 members
Articles / Desktop Programming / WPF

Drag and Drop in WPF - Part II

Rate me:
Please Sign up or sign in to vote.
4.94/5 (41 votes)
11 Nov 2009BSD4 min read 259.2K   11.4K   70  
An article showing how to add drag and drop to a WPF application using the GongSolutions.Wpf.DragDrop library.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
using System.Reflection;

namespace GongSolutions.Wpf.DragDrop.Utilities
{
    public class TypeUtilities
    {
        public static IEnumerable CreateDynamicallyTypedList(IEnumerable source)
        {
            Type type = GetCommonBaseClass(source);
            Type listType = typeof(List<>).MakeGenericType(type);
            MethodInfo addMethod = listType.GetMethod("Add");
            object list = listType.GetConstructor(Type.EmptyTypes).Invoke(null);

            foreach (object o in source)
            {
                addMethod.Invoke(list, new[] { o });
            }

            return (IEnumerable)list;
        }

        public static Type GetCommonBaseClass(IEnumerable e)
        {
            Type[] types = e.Cast<object>().Select(o => o.GetType()).ToArray<Type>();
            return GetCommonBaseClass(types);
        }

        public static Type GetCommonBaseClass(Type[] types)
        {
            if (types.Length == 0)
                return typeof(object);

            Type ret = types[0];

            for (int i = 1; i < types.Length; ++i)
            {
                if (types[i].IsAssignableFrom(ret))
                    ret = types[i];
                else
                {
                    // This will always terminate when ret == typeof(object)
                    while (!ret.IsAssignableFrom(types[i]))
                        ret = ret.BaseType;
                }
            }

            return ret;
        }
    }
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The BSD License


Written By
United Kingdom United Kingdom
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions