IDestinationTypeProvider не работает в расширении разметки wpf? - PullRequest
0 голосов
/ 16 января 2020

Я пытался использовать App.config из xaml, сначала это было просто return ConfigurationManager.AppSettings[this.Key], но оказалось, что оно не работает, когда вы пытаетесь отправить его в свойство, которое ожидает значение числового значения c, поэтому я перед возвращением пришлось выполнить преобразование в нужный тип.

Теперь у меня есть следующий код:

using System;
using System.Configuration;
using System.Windows.Markup;
using System.Xaml;

[MarkupExtensionReturnType(typeof(object))]
public class AppConfigValueExtension : MarkupExtension
{
    [ConstructorArgument("key")]
    public string Key { get; set; }

    public AppConfigValueExtension(string key)
    {
        this.Key = key;
    }

    public override object ProvideValue(IServiceProvider serviceProvider)
    {
        if (serviceProvider.GetService(typeof(IDestinationTypeProvider)) is IDestinationTypeProvider destinationTypeProvider)
        {
            return Convert.ChangeType(ConfigurationManager.AppSettings[this.Key], destinationTypeProvider.GetDestinationType());
        }
        else
        {
            throw new Exception(); // has to be changed but don't mind it
        }
    }
}

Теперь вы можете использовать расширение разметки, выполнив AProperty="{markupExtensions:AppConfigValue SomeKey}", учитывая, что вы определили xmlns для markupExtensions (xmlns:markupExtensions="clr-namespace:MarkupExtension's namespace") при запуске я получаю NullReferenceException со следующей трассировкой стека:

в MS.Internal.Xaml.Context.ObjectWriterContext .GetDestinationType () в MS.Internal.Xaml.ServiceProviderContext.GetDestinationType () в namepsace MarkupExtension.AppConfigValueExtension.ProvideValue (IServiceProvider serviceProvider) в MS.Internal.Xaml.Runtime.ClrObjectRuntime.CallProvideValue (MarkupExtension me, IServiceProvider serviceProvider)

В моем конкретном c случае я использовал xaml <Setter Property="MinWidth" Value={markupExtensions:AppConfigValue SomeKey}/> и SomeKey, установленный в 200 в файле App.config

Что происходит неправильно или что должно Я делаю, чтобы это исключение не было вызвано кодом Microsoft?

...