Search code examples
c#wpfxamlprivate

What does x:FieldModifier="Private" do and should I worry about it?


I'm currently checking my WPF project for Resharper messages and it tells me that every inputcontrol can be made private. When I do this, it adds x:FieldModifier="Private" to the control node.

I'm not that experienced with XAML. What is x:FieldModifier? What happens if I set it to Private? Is this important? Can it break stuff?


Solution

  • When the XAML-enabled compilers (e.g. C#, VB.NET) process an application with XAML files, much of the content of XAML files gets translated into temporary code written in the host language (e.g. C#, VB.NET). That is, the XAML files get transformed into ordinary CLI classes.

    As explained in the docs, the x:FieldModifier directive influences the visibility of classes or members of these classes generated from XAML definitions.

    In general, the principles of information hiding and encapsulation suggest that only what is definitely needed should be visible to the outer world (outside of a given class, for example), while anything else should remain hidden (so it can be exchanged at a later point in time without breaking the public interface of a component). That is what ReSharper tries to enforce here, as input controls are often only ever accessed from within a given user control or window. Hence, the change is important for a clean code that lends itself to a high degree of maintainability.

    One subtle way this can "break stuff" is that usually, XAML files are independent of the underlying programming language they are used with. Normally, you could translate the C# code of your application to another CLI-compatible language and simply keep using the XAML files (if the respective compiler also supports XAML, that is). By using the x:FieldModifier directive, you break that independence, as the value for that directive is language-dependent:

    The exact string you pass to specify TypeAttributes.Public versus TypeAttributes.NotPublic varies, depending on the code-behind programming language that is used.