Создание свойства зависимости в пользовательском элементе управления типа String, но отображается в обозревателе свойств как поле со списком - PullRequest
1 голос
/ 08 июня 2019

Для моих целей Enum не будет работать как тип, поскольку возможные значения неизвестны во время выполнения.

Я начал с информации, предоставленной в ответе на Создать UserControl DependencyProperty, значение которого можно выбрать в раскрывающемся списке (как поле со списком) , который задавал те же вопросы, но пользователь был удовлетворен, используя Enum и ответ с использованием преобразователя типов не очень-то помогли мне.

Мой DP (довольно просто):

    [TypeConverterAttribute(typeof(DataSourceTypeConverter))]
    public string dataSource
    {
        get { return (string)GetValue(dataSourceProperty); }
        set { SetValue(dataSourceProperty, value); }
    }

    // Using a DependencyProperty as the backing store for dataSource.  This enables animation, styling, binding, etc...
    public static readonly DependencyProperty dataSourceProperty =
        DependencyProperty.Register("dataSource", typeof(string), typeof(StatScreenDataElement), new PropertyMetadata(string.Empty));

И TypeConverter

public class DataSourceTypeConverter : TypeConverter
{
    public override StandardValuesCollection GetStandardValues(ITypeDescriptorContext context)
    {
        List<string> dataSources = new List<string>();
        dataSources.Add("Test 1");
        dataSources.Add("Test 2");
        return new StandardValuesCollection(dataSources);
    }

    public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
    {
        if (sourceType == typeof(string))
        {
            return true;
        }
        return base.CanConvertFrom(context, sourceType);
    }

    public override bool GetStandardValuesExclusive(ITypeDescriptorContext context)
    {
        return true;
    }

    public override bool GetStandardValuesSupported(ITypeDescriptorContext context)
    {
        return true;
    }
}

Я не могу отобразить DP в качестве раскрывающегося списка в браузере свойств, и при вводе чего-либо в него возвращается:

System.NotSupportedException: 'DataSourceTypeConverter не может преобразовать из System.String.'

...