WPF useful Extension methods

W

It is quite common the need of several extension methods in WPF which could help you develop faster and better apps without strange workarounds. Below I list some of them that are where quite important for me during the years.

public static DependencyObject FindVisualAncestor(this DependencyObject wpfObject, Predicate<DependencyObject> condition)
{
    while (wpfObject != null)
    {
        if (condition(wpfObject))
            return wpfObject;
        wpfObject = VisualTreeHelper.GetParent(wpfObject);
    }
    return null;
}
public static string[][] GetObjPropertiesFields(this object arg)
{
    int i = 0;
    JObject jsonObj = JObject.Parse(JsonConvert.SerializeObject(arg));
    Dictionary<string, string> dictObj = jsonObj.ToObject<Dictionary<string, string>>();
    string[] keys = new string[jsonObj.Count];
    string[] values = new string[jsonObj.Count]; ;

    foreach (KeyValuePair<string, string> kvp in dictObj)
    {
        keys[i] = kvp.Key;
        values[i++] = kvp.Value;
    }
    return new string[][] { keys, values };
}
public static RoutedEventHandlerInfo[] GetRoutedEventHandlers(UIElement element, RoutedEvent routedEvent)
{
    var eventHandlersStoreProperty = typeof(UIElement).GetProperty(
                "EventHandlersStore", BindingFlags.Instance | BindingFlags.NonPublic);
            object eventHandlersStore = eventHandlersStoreProperty.GetValue(element, null);

     var getRoutedEventHandlers = eventHandlersStore.GetType().GetMethod(
                "GetRoutedEventHandlers", BindingFlags.Instance | BindingFlags.Public 
                 | BindingFlags.NonPublic);
     var routedEventHandlers = (RoutedEventHandlerInfo[])getRoutedEventHandlers.Invoke(
                eventHandlersStore, new object[] { routedEvent });

     return routedEventHandlers;
}
public static bool RetryIfFailed(Func<bool> lamda, int times, int delay)
{
    while (lamda() == false)
    {
        Thread.Sleep(delay);
        if (times == 0)
            return false;
        times--;
    }
    return true;
}
public static Stream ToStream(this string s)
{
    var stream = new MemoryStream();
    var writer = new StreamWriter(stream);
    writer.Write(s);
    writer.Flush();
    stream.Position = 0;
    return stream;
}
public static long DateToLong(DateTime arg, bool rebaseTo2000)
{
    DateTime d2000 = new DateTime(2000, 1, 1).ToUniversalTime();
    DateTime utcnow = arg.ToUniversalTime();
    return rebaseTo2000 == false
                ? ((DateTimeOffset)utcnow).ToUnixTimeSeconds()
                : ((DateTimeOffset)utcnow).ToUnixTimeSeconds() - ((DateTimeOffset)d2000).ToUnixTimeSeconds();
}

public static DateTime LongToDate(long arg)
{
    DateTime d2000 = new DateTime(2000, 1, 1).ToUniversalTime();
    return (arg < ((DateTimeOffset)d2000).ToUnixTimeSeconds())
           ? d2000.AddSeconds(arg).ToLocalTime()
           : (DateTimeOffset.FromUnixTimeSeconds(arg)).DateTime.ToLocalTime();
}
public static byte[] HexToByteArray(this string hex)
{
    if (hex.Length % 2 == 1)
        return null;

    byte[] arr = new byte[hex.Length >> 1];

    for (int i = 0; i < hex.Length >> 1; ++i)
        arr[i] = (byte)((GetHexVal(hex[i << 1]) << 4) + (GetHexVal(hex[(i << 1) + 1])));

    return arr;
}
public static T[] SubArrayDeepClone<T>(this T[] data, int index, int length)
{
    try
    {
        T[] arrCopy = new T[(data.Length - index) > length ? length : data.Length - index];
        Array.Copy(data, index, arrCopy, 0, (data.Length - index) > length ? length : data.Length - index);
        using (MemoryStream ms = new MemoryStream())
        {
            var bf = new BinaryFormatter();
            bf.Serialize(ms, arrCopy);
            ms.Position = 0;
            return (T[])bf.Deserialize(ms);
        }
     }
     catch (Exception)
     {
         return default(T[]);
     }
}

public static T[] SubArray<T>(this T[] data, int index, int length)
{
    try
    {
        T[] arrCopy = new T[(data.Length - index) > length ? length : data.Length - index];
        Array.Copy(data, index, arrCopy, 0, (data.Length - index) > length ? length : data.Length - index);
        return arrCopy;
    }
    catch (Exception)
    {
        return default(T[]);
    }
}
public static BitmapImage BytesToBitmapImage(byte[] imageData)
{
    if (imageData == null || imageData.Length == 0)
        return null;
    var image = new BitmapImage();
    using (var mem = new MemoryStream(imageData))
    {
        mem.Position = 0;
        image.BeginInit();
        image.CreateOptions = BitmapCreateOptions.PreservePixelFormat;
        image.CacheOption = BitmapCacheOption.OnLoad;
        image.UriSource = null;
        image.StreamSource = mem;
        image.EndInit();
     }
     image.Freeze();
     return image;
 }
public static T FindBasedOn<T>(this List<T> list, string propertyName, object value)
{
    if (list.Count == 0)
        return default(T);

    if (list[0].HasProperty(propertyName) == false)
        return default(T);

    for (int i = 0; i < list.Count; i++)
        if (list[i].GetType().GetProperty(propertyName).GetValue(list[i]).Equals(value) == true)
            return list[i];

    return default(T);
}
Disclaimer: The present content may not be used for training artificial intelligence or machine learning algorithms. All other uses, including search, entertainment, and commercial use, are permitted.

Categories

Tags