我应该在 App.xaml 中声明转换器还是作为每个文件的资源? [英] Should I declare converters in App.xaml or as a per-file resource?

查看:51
本文介绍了我应该在 App.xaml 中声明转换器还是作为每个文件的资源?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 WPF 应用程序中声明转换器时,我应该:

When declaring converters in a WPF application, should I:

  1. 在 App.xaml(即在 )中声明所有我的转换器,以便它可用于整个应用程序
  2. Page/Window/ResourceDictionary/UserControl 等中只声明需要的转换器>资源部分
  3. 完全不同的东西
  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

关于可读性,方法 1 对我来说似乎是最好的,但我的问题是关于性能的.哪种方法在性能、内存等方面的资源效率最高?

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

推荐答案

好吧,我只是根本不在 xaml 中声明它们.相反,我还从 MarkupExtension 派生了我的转换器.像这样:

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.

仅从旧的 stackoverflow 线程中学到了这个技巧.

Learned this trick from an old stackoverflow thread only.

这篇关于我应该在 App.xaml 中声明转换器还是作为每个文件的资源?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆