Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I declare converters in App.xaml or as a per-file resource?

When declaring converters in a WPF application, should I:

  1. Declare all my converters in the App.xaml (i.e. in <Application.Resources/>) so it's available to the entire application
  2. Declare only needed converters for each Page/Window/ResourceDictionary/UserControl etc. in their Resources section
  3. Something else entirely

Regarding readability, method 1 seems the best to me, but my question is about performance. Which method is the most resource efficient in terms of performance, memory, etc.?

like image 246
Shimmy Weitzhandler Avatar asked Nov 02 '09 03:11

Shimmy Weitzhandler


People also ask

How do I add resources to XAML dictionary?

Tip You can create a resource dictionary file in Microsoft Visual Studio by using the Add > New Item… > Resource Dictionary option from the Project menu. Here, you define a resource dictionary in a separate XAML file called Dictionary1. xaml.

What is app XAML used for?

What is XAML? Extensible Application Markup Language (XAML) is the language used to define your app's user interface. It can be entered manually, or created using the Visual Studio design tools.

What are convertors in WPF?

The WPF converters acts as a bridge between the source and the target if the source and target have different data formats or need some conversion. For example, sometimes we need to convert data from one format to another format, when it flows from the source to the target or vice-versa the conversion is required.


1 Answers

Well, I just don't declare them in xaml at all. Instead, I additionally derive a converter of mine from MarkupExtension. Like this:

public class MyValueConverter : MarkupExtension, IValueConverter
{
    private static MyValueConverter _converter = null;
    public override object ProvideValue(IServiceProvider serviceProvider)
    {
        if (_converter == null) _converter = new MyValueConverter();    
        return _converter;
    }

    public object Convert
     (object value, Type targetType, object parameter, CultureInfo culture) { }
    public object ConvertBack
     (object value, Type targetType, object parameter, CultureInfo culture) { }
}

This allows me to use my converter anywhere, like this:

Source="{Binding myValue, Converter={converters:MyValueConverter}}"

where converters is the namespace in which I have declared my converter.

Learned this trick from an old stackoverflow thread only.

like image 128
Yogesh Avatar answered Oct 25 '22 20:10

Yogesh