Мне нужен доступ к закрытому элементу (выделенному элементу) поля со списком - PullRequest
11 голосов
/ 17 февраля 2011

Я реализую навигацию по клавишам для приложения и хочу переопределить функциональность клавиши пробела, когда поле со списком сфокусировано так, что оно действует как клавиша ввода; как это:

if (!cb.IsDropDownOpen)
{
  cb.IsDropDownOpen = true;
}
else
{
  cb.SelectedItem = cb.{non-public member HighlightedItem};
  cb.IsDropDownOpen = false;
}

Проблема в том, что мне нужно получить значение этого непубличного члена, чтобы я мог установить выбранное значение и закрыть раскрывающийся список (как обычно будет работать ввод).

Теперь вопрос: что является самым быстрым и беспроблемным способом достижения этого?

Ответы [ 2 ]

18 голосов
/ 17 февраля 2011

Это вспомогательный класс, который я использую для этого:

public static class PropertyHelper
{
    /// <summary>
    /// Returns a _private_ Property Value from a given Object. Uses Reflection.
    /// Throws a ArgumentOutOfRangeException if the Property is not found.
    /// </summary>
    /// <typeparam name="T">Type of the Property</typeparam>
    /// <param name="obj">Object from where the Property Value is returned</param>
    /// <param name="propName">Propertyname as string.</param>
    /// <returns>PropertyValue</returns>
    public static T GetPrivatePropertyValue<T>(this object obj, string propName)
    {
        if (obj == null) throw new ArgumentNullException("obj");
        PropertyInfo pi = obj.GetType().GetProperty(propName,
                                                    BindingFlags.Public | BindingFlags.NonPublic |
                                                    BindingFlags.Instance);
        if (pi == null)
            throw new ArgumentOutOfRangeException("propName",
                                                  string.Format("Property {0} was not found in Type {1}", propName,
                                                                obj.GetType().FullName));
        return (T) pi.GetValue(obj, null);
    }

    /// <summary>
    /// Returns a private Field Value from a given Object. Uses Reflection.
    /// Throws a ArgumentOutOfRangeException if the Property is not found.
    /// </summary>
    /// <typeparam name="T">Type of the Field</typeparam>
    /// <param name="obj">Object from where the Field Value is returned</param>
    /// <param name="propName">Field Name as string.</param>
    /// <returns>FieldValue</returns>
    public static T GetPrivateFieldValue<T>(this object obj, string propName)
    {
        if (obj == null) throw new ArgumentNullException("obj");
        Type t = obj.GetType();
        FieldInfo fi = null;
        while (fi == null && t != null)
        {
            fi = t.GetField(propName, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
            t = t.BaseType;
        }
        if (fi == null)
            throw new ArgumentOutOfRangeException("propName",
                                                  string.Format("Field {0} was not found in Type {1}", propName,
                                                                obj.GetType().FullName));
        return (T) fi.GetValue(obj);
    }

    /// <summary>
    /// Sets a _private_ Property Value from a given Object. Uses Reflection.
    /// Throws a ArgumentOutOfRangeException if the Property is not found.
    /// </summary>
    /// <typeparam name="T">Type of the Property</typeparam>
    /// <param name="obj">Object from where the Property Value is set</param>
    /// <param name="propName">Propertyname as string.</param>
    /// <param name="val">Value to set.</param>
    /// <returns>PropertyValue</returns>
    public static void SetPrivatePropertyValue<T>(this object obj, string propName, T val)
    {
        Type t = obj.GetType();
        if (t.GetProperty(propName, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance) == null)
            throw new ArgumentOutOfRangeException("propName",
                                                  string.Format("Property {0} was not found in Type {1}", propName,
                                                                obj.GetType().FullName));
        t.InvokeMember(propName,
                       BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.SetProperty |
                       BindingFlags.Instance, null, obj, new object[] {val});
    }


    /// <summary>
    /// Set a private Field Value on a given Object. Uses Reflection.
    /// </summary>
    /// <typeparam name="T">Type of the Field</typeparam>
    /// <param name="obj">Object from where the Property Value is returned</param>
    /// <param name="propName">Field name as string.</param>
    /// <param name="val">the value to set</param>
    /// <exception cref="ArgumentOutOfRangeException">if the Property is not found</exception>
    public static void SetPrivateFieldValue<T>(this object obj, string propName, T val)
    {
        if (obj == null) throw new ArgumentNullException("obj");
        Type t = obj.GetType();
        FieldInfo fi = null;
        while (fi == null && t != null)
        {
            fi = t.GetField(propName, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
            t = t.BaseType;
        }
        if (fi == null)
            throw new ArgumentOutOfRangeException("propName",
                                                  string.Format("Field {0} was not found in Type {1}", propName,
                                                                obj.GetType().FullName));
        fi.SetValue(obj, val);
    }
}
13 голосов
/ 17 февраля 2011

Вы должны использовать отражение, чтобы получить значение свойства

PropertyInfo highlightedItemProperty = cb.GetType().GetProperties(BindingFlags.NonPublic  | BindingFlags.Instance).Single(pi => pi.Name == "HighlightedItem");
object highlightedItemValue = highlightedItemProperty.GetValue(cb, null);

Для просмотра всех свойств или полей также проверьте

var allProps = cb.GetType().GetProperties(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance).OrderBy(pi => pi.Name).ToList();
var allFields = cb.GetType().GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance).OrderBy(pi => pi.Name).ToList();

(вы можете прочитать их все в отладчике)

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...