user1721413
user1721413

Reputation:

How to use a C# custom subclass in XAML?

Here is my issue : I would like to use a subclass of SurfaceInkCanvas in my MyWindow. I created a C# class like this :

namespace MyNamespace
{
    public class SubSurfaceInkCanvas : SurfaceInkCanvas
    {
       private MyWindow container;

       public SubSurfaceInkCanvas()
           : base()
       {
       }

       public SubSurfaceInkCanvas(DrawingWindow d) : base()
       {
           container = d;
       }

       protected override void OnTouchDown(TouchEventArgs e)
        {
            base.OnTouchDown(e);     
        }
    }
}

And I would like to use it in my XAML window. Is it something like this ?

<MyNamespace:SubSurfaceInkCanvas
    x:Name="canvas"
    Background="White"
    TouchDown="OnTouchDown"/>

Am I totally on the wrong way ?

Upvotes: 9

Views: 9510

Answers (2)

myermian
myermian

Reputation: 32505

You need to import an Xml Namespace in order to use classes...

<Window x:Class="Namespace.SomeWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"> ... </Window>

Notice how the namespaces are imported. The default one (no prefix) can be whatever you want, but it's probably best to leave that to Microsoft's presentation namespace. Then there is the "x" namespace, which is the base xaml namespace (of course you could change the prefix, but you should leave it as it is).

So, in order to add your own namespace to it there are two ways of doing it (one if it's local).

  • CLR-Namespaces: xmlns:<prefix>="clr-namespace:<namespace>;Assembly=<assemblyName>"
  • URI-Namespaces: xmlns:<prefix>="<uri>"

In your case you'd probably want to set the prefix as "local" and use the CLR Namespace (since it is all you can use).

Import: xmlns:local="clr-namespace:MyNamespace;Assembly=???"
Usage: <local:SubSurfaceInkCanvas ... />


Alternatively, if these classes are inside of an external library, you can map your CLR-Namespaces to XML-Namespaces... see this answer for an explenation on that.

Upvotes: 9

Johan Larsson
Johan Larsson

Reputation: 17580

You need to add the namespace (xmlns:myControls), try like this:

<Window ...
        xmlns:myControls="clr-namespace:MyNamespace;assembly=MyNamespace"
        ...>
    <myControls:SubSurfaceInkCanvas x:Name="canvas"
                                    Background="White"
                                    TouchDown="OnTouchDown"/>
</Window>

Upvotes: 3

Related Questions