WPF
You want the IsReadOnly
property, not the ReadOnly
property.
For example:
- Create a new
WPF App (.NET Framework)
project called DeleteMe
- In
MainWindow.xaml
, delete the Grid
- In
MainWindow.xaml.cs
, use this code:
using System.ComponentModel;
using System.Windows;
using System.Windows.Controls;
namespace DeleteMe
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
var tm = new TextBoxMoeda();
this.AddChild(tm);
tm.SomenteLeitura = true;
}
public class TextBoxMoeda : TextBox
{
[Category("TextBoxMoeda")]
public virtual bool SomenteLeitura
{
get => base.IsReadOnly;
set
{
base.IsReadOnly = value;
}
}
}
}
}
The textbox will be readonly (i.e. I can't type anything into the textbox).
WinForms
The code already appears to work in WinForms. These steps will produce a working project:
- Create a new
Windows Forms App
project called DeleteMeAgain
- Overwrite all of the
Form1.cs
code with this:
using System.ComponentModel;
using System.Windows.Forms;
namespace DeleteMeAgain
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
var tm = new TextBoxMoeda();
this.Controls.Add(tm);
tm.SomenteLeitura = true;
}
public class TextBoxMoeda : TextBox
{
[Category("TextBoxMoeda")]
public virtual bool SomenteLeitura
{
get => base.ReadOnly;
set
{
base.ReadOnly = value;
Invalidate();
}
}
}
}
}
The textbox will be readonly (i.e. I can't type anything into the textbox).
Windows Form: User Control
Do this:
- Create a new
Windows Forms App
called DeleteMe3
- Set
Target Framework
to .NET Core 3.1 (Long-term support)
- In your project, create a new UserControl with the filename
TextBoxStack.cs
- Overwrite all of the code for that user control with this:
using System.ComponentModel;
using System.Windows.Forms;
namespace DeleteMe3
{
public partial class TextBoxStack : TextBox
{
[Category("TextBoxStack")]
public virtual bool SomenteLeitura
{
get => base.ReadOnly;
set
{
base.ReadOnly = value;
Invalidate();
}
}
}
}
- An error will appear. Go to the source of the error and delete that line.
- Build the solution
- Add your new user control to
Form1
- Select the new user control on the form
- Change the
SomenteLeitura
property to True
- Run the project. The textbox should be grey and readonly.