我应该在 App.xaml 中声明转换器还是作为每个文件的资源? [英] Should I declare converters in App.xaml or as a per-file resource?
问题描述
在 WPF 应用程序中声明转换器时,我应该:
When declaring converters in a WPF application, should I:
- 在 App.xaml(即在
)中声明所有我的转换器,以便它可用于整个应用程序 - 在
Page
/Window
/ResourceDictionary
/UserControl
等中只声明需要的转换器>资源部分 - 完全不同的东西
- Declare all my converters in the App.xaml (i.e. in
<Application.Resources/>
) so it's available to the entire application - Declare only needed converters for each
Page
/Window
/ResourceDictionary
/UserControl
etc. in theirResources
section - 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屋!