How to set read-only content

SyntaxEditor for WPF Forum

The latest build of this product (v25.1.1) was released 3 months ago, which was before this thread was created.
Posted 21 days ago by Chris
Version: 25.1.1
Avatar

Hi, I have a requirement where I want to disable or make certain sections of content in an editor read-only, so that only certain content can be edited. Is there any way to achieve this? Thank you.

For example, in the following C# class, I want to only edit the function body and not the rest of the content.

using System.Text.Json;

namespace Example
{
    public class Test
    {    
        // editable content
    }
}

Comments (1)

Answer - Posted 20 days ago by Actipro Software Support - Cleveland, OH, USA
Avatar

Hi Chris,

There are two options for how to implement this.

1) Code Fragments - The first option is the easiest and cleanest way to do things, and is best if you are ok with hiding the "header" and "footer" text like your imports, namespace, and class declarations from the end user.  With this option you only show the editable content area in the document.  The header and footer text is prepended and appended respectively to the document text when the document is being parsed.  The Code Fragments QuickStart sample shows how to implement that.

2) Read-only regions - The second option is better if you want to keep all the document text fully visible.  Check out the Read-Only Regions QuickStart sample.  You can tag regions to be non-editable.  If you tagged the start of the document through the second curly brace, and the related end curly brace through the end of the document, it would only allow editing within the editable content area. 

While the regions won't let you edit within them, one note in that sample is that you could still edit at the very start and end of the document, just outside the tagged ranges.  To account for that, you'd have to also add some handler like this that would block any edit operations at the start/end of the document:

editor.Document.TextChanging += (sender, e) => {
	foreach (var operation in e.TextChange.Operations) {
		if (!operation.IsProgrammaticTextReplacement) {
			if (
				(operation.StartOffset == 0) 
				|| (operation.DeletionEndOffset == editor.Document.CurrentSnapshot.Length)
				|| (operation.InsertionEndOffset == editor.Document.CurrentSnapshot.Length)
			) {
				e.Cancel = true;
			}
		}
	}
};


Actipro Software Support

Add Comment

Please log in to a validated account to post comments.