Make use of the x:FieldModifier attribute

When you give an element a name in XAML, either via the Name property or the x:Name attribute, what you are really doing is supplying a field name for the class into which the XAML is converted.  By default, for whatever reason, those fields are given the “internal” access modifier.  This means that any type within the assembly that contains that class is able to access those elements.  If you appreciate the idea of encapsulation, this is clearly not a good thing!

You can use a little-known attribute called x:FieldModifier to remedy the problem.  By setting x:FieldModifier to “private” the field which references that element will be a private member of the class to which the XAML belongs.  I highly recommend doing this whenever possible, since it promotes a properly designed API for your classes that have a XAML partial.

For example, consider the following XAML:

xaml

If you look in the generated file for the Window that contains this XAML, you’ll find the following two fields:

generated code

As you can see, the x:FieldModifier determines which access modifier is applied to the fields that have a name in XAML.  The modifiers do not impact the ability to bind against the fields using an ElementName binding.  Since there is no downside to doing this, there’s no reason not to do it.

About these ads

8 Responses to Make use of the x:FieldModifier attribute

  1. Paul Kohler says:

    Good call. I had not spotted that default.

    So… do you happen to know the 1 line of XAML that will apply the FieldModifier of private to all controls by default! ;-)

  2. Josh Smith says:

    No…is there one?

  3. Paul Kohler says:

    None I know of. Its an MSBUILD thing and I don’t know that the default in configurable…

  4. I really wish there was a way to make it private by default. I remember falling off my chair when discovering it was internal by default. Ridiculous.

  5. Dan says:

    Great suggestion J.S.!
    Thanks

  6. peteohanlon says:

    I’ve updated MoXAML PowerToys to apply x:FieldModifier = “private” to all x:Name fields in a project. You can get it here, http://peteohanlon.wordpress.com/moxaml-power-toys/.

  7. Neil Mosafi says:

    Wow, had no idea about that! Can that be set by a global style by any chance?

  8. Josh Smith says:

    @Pete: Cool! Nice idea.

    @Neil: There’s no global way to change that, afaik.

Follow

Get every new post delivered to your Inbox.

Join 290 other followers

%d bloggers like this: