开发者

What is more efficient {X:Static Class.Default} or {StaticResource Class}?

Suppose I have class I want to reference in XAML.

public class MyConverter
{
  public static readonly MyConverter Default = new MyConverter();
  ...
};

And then in XAML I can reference it either

<Label 开发者_高级运维Content="{Binding Text,Converter={x:Static local:MyConverter.Default}"/>

or

<local:MyConverter x:Key="MyConverter"/>
...
<Label Content="{Binding Text,Converter={StaticResource local:MyConverter}"/>

Which way is more efficient?


I doubt anything here will be more effecient than other but the key difference here is what is actually going on:

  1. In first approach you're referencing static field of class MyConverter
  2. In second case you're creating an instance of MyConverter and using it.

I believe first one might couple percents faster (or what do you mean by efficient?) but this difference won't give you much profit. I would choose option #1 if you already have a static field. Also as far as I remember x:Static still is not available in Silverlight.


I find the first option interesting as it provides a nice and clean possibility to use the class for different variations of a task in combination with a singleton. Imagine a visiblity value converter like this:

public class VisibilityConverter : IValueConverter
{
    private static readonly VisibilityConverter defaultInstance = new VisibilityConverter();

    public static VisibilityConverter Default = new VisibilityConverter();
    public static VisibilityConverter InverseBoolean = new VisibilityConverter() { Inverse = true };

        public bool Inverse { get; set; }

        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            var isVisible = value != null
                && value.GetType() == typeof(bool)
                && (bool)value;

            if (Inverse)
            {
                isVisible = !isVisible;
            }

            return isVisible ? System.Windows.Visibility.Visible : System.Windows.Visibility.Collapsed;
        }

This can then easily be used in a default and in a inverse mode:

Converter={x:Static converters:VisibilityConverter.Default}
Converter={x:Static converters:VisibilityConverter.InverseBoolean}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜