Using Value Converters in WPF without having to define them as resources first

后端 未结 4 956
春和景丽
春和景丽 2020-12-09 04:20

Is it possible to use value converters without having to define them beforehand as resources?

Right now I have


    

        
4条回答
  •  时光说笑
    2020-12-09 04:30

    I don't know of a way to do this the way your are stating, but I just tried this as a sample and it worked. In your App.xaml.cs file you can create a method that uses reflection to load the converters.

    private void Application_Startup(object sender, StartupEventArgs e)
    {
        LoadConverters();
    }
    
    private void LoadConverters()
    {
        foreach(var t in Assembly.GetExecutingAssembly().GetTypes())
        {
            if (t.GetInterfaces().Any(i => i.Name == "IValueConverter"))
            {
                Resources.Add(t.Name, Activator.CreateInstance(t));
            }
        }
    }
    

    Then you can use the converter with like this, half way there I guess.

    The problem with the approach you are proposing is that the Xaml parser doesn't know when and how many instances of your converter to create. Creating it as a resource ensure only one instance.

提交回复
热议问题