How to use native C # subclass in XAML?

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

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 completely mistaken?

+6
source share
2 answers

You need to import the Xml namespace in order to use the 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 namespaces are imported. The default value (without a prefix) may be whatever you want, but it's probably best to leave this in the Microsoft Presentation namespace. Then there is the namespace "x", which is the base xaml namespace (of course, you can change the prefix, but you must leave it as it is).

So, to add your own namespace to it, there are two ways to do this (one if it's local).

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

In your case, you probably want to set the prefix as “local” and use the CLR namespace (since that’s all you can use).

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


Alternatively, if these classes are inside an external library, you can map your CLR namespaces to XML namespaces ... see this answer for an explanation of what.

+7
source

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

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

All Articles