27

I'm trying to access a control's text property from program.cs and it says that it is inaccessible due to protected level. How can I fix this please?

Abel
  • 56,041
  • 24
  • 146
  • 247
user164203
  • 313
  • 1
  • 4
  • 7

4 Answers4

36

This is the default property for controls and can be solved by:

  1. Going into Design-View for the Form that contains the specified Control
  2. Then changing the Control's Modifiers property to Public or Internal.

Control Properties > Modifiers Screenshot

Peter Duniho
  • 68,759
  • 7
  • 102
  • 136
jay_t55
  • 11,362
  • 28
  • 103
  • 174
  • 4
    Note: just to emphasize as this seems to have been very unclear by the asker, this is the *control's instance itself* that's protected (i.e., the variable holding the control), not the *`.Text` property*, which is public. – Abel Nov 16 '09 at 17:35
  • It is worth pointing out for SEO that this works in xamarin XAML as well – lucidbrot Apr 12 '19 at 08:12
  • Tried this for textbox and got the error "An object reference is required for the nonstatic field, method, or property 'textbox' – SimonKravis Aug 11 '23 at 23:42
6

Control Protection level Resolved

Go to designer file search control By ID e.g txtModel change protected modifier to public modifier

Asad
  • 91
  • 2
  • 5
  • 3
    This is not a good idea. Better is to access value of control thru property of class, where control is used. – eridanix Sep 22 '12 at 21:25
  • @asad It is not a good idea to access the child controls directly because you cannot change/maintain/modify the child without updating the grandparent. This is encapsulation. – Brian Leeming Jul 19 '16 at 13:36
3

Use x:FieldModifier="public" e.g.

<TextBlock x:FieldModifier="public" x:Name="AccessibleTextBlock" />

as explained here: Modifying XAML named field visibility

In my case, I put UserControl in another DLL. WPF’s convention is to set all named fields as internal by default. Using the x:FieldModifier="public" has solved the issue.

Michael G
  • 129
  • 10
1

The concept behind is the protection level. As we have studied in Object Oriented Paradigm keep your class members variables private and set or get it from Property.Thats why it is not a good approach

Asad
  • 91
  • 2
  • 5