Skip to content

Custom Platform Controls

cwensley edited this page Sep 2, 2012 · 12 revisions

Eto.Forms comes with many standard controls, however sometimes you may want to make full use of each platform's abilities, or if you want to re-use platform specific code already written. Custom platform controls can be created for this purpose.

Custom platform controls can have implementations for each platform, and are implemented exactly the way standard Eto.Forms controls are. You can either extend an existing control and provide a custom handler for each platform, or create a completely custom control.

All supportable Eto.Forms control handlers are registered through the Generator class. When creating a new Eto.Forms control (custom or not), the Generator looks up the control handler via it's interface type. Generators will scan the platform assembly for the handlers, however you can also add your own directly.

The drawback of creating custom platform controls is that you have to create a handler implementation of the control for each platform you wish to use it with.

In your cross-platform library:

public interface IMyCustomControl : IControl
{
	string MyProperty { get; set; }
}

public class MyCustomControl : Control
{
	public MyCustomControl ()
		: this (Generator.Current)
	{
	}

	public MyCustomControl (Generator generator)
		: base (generator, typeof (IMyCustomControl))
	{
	}

	public string MyProperty
	{
		get { return handler.MyProperty; }
		set { handler.MyProperty = value; }
	}
}

In your MonoMac platform assembly:

public class MyCustomControlHandler : MacControl <NSTextField, MyCustomControl>, IMyCustomControl
{
	public MyCustomControlHandler ()
	{
		this.Control = new NSTextField ();
	}
	
	public string MyProperty
	{
		get { return this.Control.StringValue; }
		set { this.Control.StringValue = value ?? string.Empty; }
	}
}

In your WPF assembly:

public class MyCustomControlHandler : WpfControl<Microsoft.Windows.Controls.TextBox, MyCustomControl>, IMyCustomControl
{
	public MyCustomControlHandler ()
	{
		this.Control = new Microsoft.Windows.Controls.TextBox ();
	}
	
	public string MyProperty
	{
		get { return this.Control.Text; }
		set { this.Control.Text = value; }
	}
}

To register your new control, you must add it to the generator. This can be done before creating your application in your main() method.

var myGenerator = new Eto.Platform.Mac.Generator (); // mac generator

// to register your handler, call this before using your class:
myGenerator.Add<IMyCustomControl>(typeof(MyCustomControlHandler));

// or, add the entire assembly (will scan for all IWidget-derived classes):
myGenerator.AddAssembly (myMacPlatformAssembly);

// create application object, and run