[英]Xamarin / C# extending an existing class
我最近学习 C# 有一段时间了,最近是MVVM
但我未能掌握有关扩展类的知识,显然......
在下面的示例中, SkiaSharp
是一个 Xamarin 矢量图形包,我提供了一些矢量图标,我希望有一个可重用的类来在应用程序的各个点对它们进行缩放和着色
我想如果我将“SKCanvasView”子类化,那么我可以传入变量(图标、颜色)——当代码在相关视图中时一切正常,但我希望它在共享代码中,所以我像这样引用它
<ContentView xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:d="http://xamarin.com/schemas/2014/forms/design"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
xmlns:local="clr-namespace:Custom"
x:Class="NavigationIcons">
<local:RenderSVG StyleId="F9001A"
Grid.Row="0"
Grid.Column="1"
HorizontalOptions="CenterAndExpand"
VerticalOptions="CenterAndExpand"
ClassId="vector.svg"
PaintSurface="OnCanvasViewPaintSurface">
</local:RenderSVG>
它构建,但随后它抱怨“PaintSurface”的方法不在视图代码隐藏文件中,当然,如果它引用另一个类,我认为不需要
我会假设"local:SVGRender"
意味着所有代码都将从该共享类运行,而不是从 XAML 视图后面的类文件运行,但它似乎不是?
public class RenderSVG : SKCanvasView
{
void OnCanvasViewPaintSurface(object sender, SKPaintSurfaceEventArgs args)
{
try
{
// rendering code is here
}
}
}
抛出的错误是“EventHandler”Custom.RenderSVG.OnCanvasViewPaintSurface”,在“NavigationIcons”类型中找不到正确的签名,所以它甚至没有试图查看我制作的派生类
正如@FreakyAli 所说, PaintSurface
是一个事件。 在ContentView
使用SKCanvasView
,您将事件绑定到容器的方法(事件处理程序)。 SKCanvasView
将触发事件并调用容器方法。
但是当您SKCanvasView
您必须覆盖OnPaintSurface
。 或者,您可以在某个时候通过代码(例如在构造时)将OnCanvasViewPaintSurface
事件处理程序附加到PaintSurface
事件,并且在某个时候您还需要将其分离(在销毁之前)。 覆盖OnPaintSurface
是首选方式。 例如:
public class RenderSVG : SKCanvasView
{
protected override void OnPaintSurface(SKPaintSurfaceEventArgs args)
{
try
{
// rendering code is here
}
}
}
当然,您需要从 XAML 文件中删除PaintSurface="OnCanvasViewPaintSurface"
:
<ContentView xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:d="http://xamarin.com/schemas/2014/forms/design"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
xmlns:local="clr-namespace:Custom"
x:Class="NavigationIcons">
<local:RenderSVG StyleId="F9001A"
Grid.Row="0"
Grid.Column="1"
HorizontalOptions="CenterAndExpand"
VerticalOptions="CenterAndExpand"
ClassId="vector.svg">
</local:RenderSVG>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.