I'm trying to make a custom message box with my controls.
public static partial class Msg : Form
{
public static void show(string content, string description)
{
}
}
Actually I need to place some controls (a gridview) in this form and I have to apply my own theme for this window, so I don't want to use MessageBox
. I want to call this from my other forms like
Msg.show(parameters);
I don't wish to create an object for this form.
I know I can't inherit from Form
class because it isn't static. But I wonder how MessageBox
is implemented, because it is static. It is being called like MessageBox.show("Some message!");
Now I'm getting an error because inheritance is not allowed:
Static class 'MyFormName' cannot derive from type 'System.Windows.Forms.Form'. Static classes must derive from object
How MessageBox
is implemented then?
You don't need to make the class
static
in order to call one of its methods statically — it's sufficient to declare the particular method asstatic
.We are using
messageBox.ShowDialog()
to have the form being displayed as a modal window. You can display the message box usingDetailedMessageBox.ShowMessage("Content", "Description");
.By the way, you should rethink your naming and stick to a consistent naming pattern.
Msg
andshow
are weak names that do no match the Naming Guidelines — you would definitely want to check those out!I have just written a single file replacement for MessageBox that is a good example how to "imitate" the static interface of MessageBox. You can download it here and use it like a standard MessageBox:
http://www.codeproject.com/Articles/601900/FlexibleMessageBox-A-flexible-replacement-for-the
Regards, Jörg
In a WPF project you can add a new window and call it MessageBoxCustom then inside C# the Void where you can find InitialiseComponent(); you add 2 properties and bind those properties to the textBlocks you should have created inside your XAML view Example:
You don't need the class to be static. Just do something like:
Your form class needs not to be
static
. In fact, a static class cannot inherit at all.Instead, create an
internal
form class that derives fromForm
and provide apublic static
helper method to show it.This static method may be defined in a different class if you don't want the callers to even “know” about the underlying form.
Side note: as Jalal points out, you don't have to make a class
static
in order to havestatic
methods in it. But I would still separate the “helper” class from the actual form so the callers cannot create the form with a constructor (unless they're in the same assembly of course).