简体   繁体   中英

How can I extend the richtextbox control using system namespace only

Is there a way to extend the richtextbox control in c# using an equivalent method like below :

namespace System
{
    public static class StringExtensions
    {
        public static string PadBoth(this string str, int length)
        {
            int spaces = length - str.Length;
            int padLeft = spaces / 2 + str.Length;
            return str.PadLeft(padLeft).PadRight(length);
        }
    }
}

So something like :

namespace System.Windows.Controls
{
    public static class RichTextBoxExtensions
    {
        public static string MyCustomMethod()
        {
             return "It works!";
        }
    }
}

I know how to extend it using the old way by creating a class and inheriting the richtextbox object, however what I would prefer to do is the reverse as the above adds the functionality to the base RichTextBox object without the need to create a new custom usercontrol to extend it's functionality.

To be clear, I am not looking to do the following (or similar) :

public class Foo : RichTextBox { }

I am not sure what this method of extending is called or if it even has a specific name / classification, but it just feels more natural when objects are extended in this manner than creating new controls filling up an already bloated toolbar of hundreds of controls.

What you want is called an extension method , for instance, this method will extend the RichTextBox:

public static class RichTextBoxExtensions
{
    public static void MyCustomMethod(this RichTextBox self)
    {
        MessageBox.Show("It works, this textbox has " + self.Text + " as the text!");
    }
}

Just do like your string extension, but use a RichTextBox as the first argument:

public static string MyCustomMethod(this RichTextBox richTextBox)
{
    return richTextBox.Text;
}

Also you don't need to have the same namespace as the control, you can use your own/your project's namespace without a problem.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM