C# Generic User Control WPF C# Generic User Control WPF wpf wpf

C# Generic User Control WPF


You can use generic as if you don’t use XAML. But if you want to use XAML to define your control, you can’t use generic


I finally have a working answer.

I build the Control around a Hashtable that uses objects

then add an extension to the object class

    public static bool TryParse<TType>(this object obj, out TType result)     {        try        {            result = (TType)Convert.ChangeType(obj, typeof(TType));            return true;        }        catch        {            result = default(TType);            return false;        }    }    public static TType Parse<TType>(this object obj) where TType : struct    {        try        {            return (TType)Convert.ChangeType(obj, typeof(TType));        }        catch        {            throw new InvalidCastException("Cant cast object to " + typeof(TType).Name);        }    }

then add a generic property that calls the extension to cast the objects to a Dictionary


As Steyca mentioned, you can't use generics in XAML. You can however create your generic user control, and derive specific types from this generic class, which you can use in XAML. This at least reduces code duplication to some extent.

As a sidenote, generics in XAML might be possible if you support it yourself, by passing the Type as the value of a property. At least, I believe that's the intent of this article, but I didn't have time yet to try it out myself.