Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

override metadata in static constructor?

I have a class that inherits the TextBox Class, call it MyTextBox

I'd like to redefine the default Background value for this class.

So I looked for a way to do so and found a good option: call BackgroundProperty.OverrideMetadata()

trouble is: where can I put this?

in the App.OnStartup()? Ugly and not practical, I'd like that to be in my Class's code file.

in the Class's contructor? I get an exception:

PropertyMetadata is already registered for the type 'MyTextBox'.

(seems fine to me, I understand why I get this perfectly)

So I looked again a found about the static constructor in C# (did not no about that earlier, what a pity)

so here's my code:

public class MyTextBox : TextBox
{
    static MyTextBox()
    {
        MyTextBox.BackgroundProperty.OverrideMetadata(typeof(MyTextBox), new FrameworkPropertyMetadata(App.Current.Resources["CustomBackgroundBrush"]));
    }
}

now, I'm pretty happy whith this, but Microsoft isn't. Namely, when I use the code analysis feature, I get this:

CA1810: Initialize reference type static fields inline

Hence my question: what can I do about it?

  • ignore the warning? >> I don't like to ignore warnings
  • move the call to the overrideMetadata method? >> I'd like to, but where?

any hints welcome, thanks

Edit: I'll add that I don't fully understand why I get this warning, since I am not initializing anything per say in my static constructor, or am I?

like image 260
David Avatar asked Mar 22 '11 15:03

David


1 Answers

Here is the link from MSDN for overridding metadata for overridding metadata for a dependency property:

It states: "Overriding metadata on a dependency property must be done prior to that property being placed in use by the property system (this equates to the time that specific instances of objects that register the property are instantiated). Calls to OverrideMetadata must be performed within the static constructors of the type that provides itself as the forType parameter of OverrideMetadata."

And the wording from the link you posted to CA1810 about when to suppress warnings:

When to Suppress Warnings

CA1810 It is safe to suppress a warning from this rule if performance is not a concern; or if global state changes that are caused by static initialization are expensive or must be guaranteed to occur before a static method of the type is called or an instance of the type is created.

So, your current implementation and suppression of the warning is probably the correct route.

like image 117
dugas Avatar answered Sep 26 '22 04:09

dugas