How to use a C# custom subclass in XAML?

感情迁移 提交于 2019-12-30 06:25:30

问题


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 ?


回答1:


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.




回答2:


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>


来源:https://stackoverflow.com/questions/13351652/how-to-use-a-c-sharp-custom-subclass-in-xaml

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!