Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
842 views
in Technique[技术] by (71.8m points)

wpf - 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.?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...