Keke Zhang
Keke Zhang

Reputation: 91

Why aren't WPF controls private by default?

In WPF, writing

<TextBlock x:Name="foo"/>

will make the control public. To make it private, one must explicitly specify the FieldModifier:

<TextBlock x:Name="foo" x:FieldModifier="private"/>

I find this strange. I don't think it is a good coding style to access a subcontrol directly from outside the class. For example, I would avoid writing

var muc = new MyUserControl();
muc.foo.Text = "foo";

Instead I would write a public method and use it:

public void SetFooText(string text) { foo.Text = text; }
// in somewhere else
var muc = new MyUserControl();
muc.SetFooText("foo");

or write a public property

public string FooText 
{ 
    get { return foo.Text; } 
    set { foo.Text = value; } 
}
// in somewhere else
var muc = new MyUserControl();
muc.FooText = "foo";

So, I don't really see any advantages setting controls to public by default. Maybe it would be safer if private is the default, like everything in C#.

Why is public the default?

Edit:

Well, I made a mistake. The default is internal as others have mentioned. But the question why it is not private is still waiting for an answer.

Upvotes: 5

Views: 390

Answers (1)

Samvel Petrosov
Samvel Petrosov

Reputation: 7706

Default value of the x:FieldModifier for C# is NotPublic(Internal)

TypeAttributes.NotPublic is the default behavior because it is infrequent that code outside the assembly that compiled the XAML needs access to a XAML-created element. WPF security architecture together with XAML compilation behavior will not declare fields that store element instances as public, unless you specifically set the x:FieldModifier to allow public access.

As we see if they were private by default assembly which compiled the XAML would not have access to it XAML-created element.

You can find more information here MSDN

Upvotes: 7

Related Questions