Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why aren't WPF controls private by default?

Tags:

c#

wpf

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.

like image 969
Keke Zhang Avatar asked Apr 12 '17 04:04

Keke Zhang


People also ask

Will WPF be discontinued?

“WPF would be dead in 2022 because Microsoft doesn't need to be promoting non-mobile and non-cloud technology. But WPF might be alive in that sense if it's the best solution for fulfilling specific customer needs today. Therefore, having a hefty desktop application needs to run on Windows 7 PCs with IE 8.

Is anyone using WPF?

WPF is still one of the most used app frameworks in use on Windows (right behind WinForms).

Can I use WPF control in WinForms?

Add a WPF control to a Windows Form Your new WPF control is ready for use on the form. Windows Forms uses the ElementHost control to host WPF content. To add a WPF control to a Windows Form: Open Form1 in the Windows Forms Designer.

How can I find WPF controls by name?

FindName method of FrameworkElement class is used to find elements or controls by their Name properties. The FrameworkElement class is mother of all controls in WPF.


1 Answers

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

like image 196
Samvel Petrosov Avatar answered Sep 27 '22 02:09

Samvel Petrosov