Windows Presentation Foundation (WPF) 项目不支持 MyCanvas

MyCanvas is not supported in a Windows Presentation Foundation (WPF) project

我有自己的 Canvas 实现:

namespace FontRendererWPF
{
    public class ImageCanvas : Canvas
    {
        string _imagePath;

        public string ImagePath
        {
            get { return _imagePath; }
            set
            {
                _imagePath = value;
                InvalidateVisual();
            }
        }

        protected override void OnRender(DrawingContext dc)
        {
            if (_imagePath == null)
                return;

            BitmapImage img = new BitmapImage(new Uri(_imagePath));
            dc.DrawImage(img, new Rect(0, 0, img.PixelWidth, img.PixelHeight));
        }
    }
}

我刚刚将 MainWindow.xaml 中的元素从 Canvas 重命名为 ImageCanvas:

<Window x:Class="FontRendererWPF.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MyApp" Height="350" Width="525">
    <Grid>               
        <ImageCanvas x:Name="canvas" Margin="10,83,7,5" Background="{DynamicResource {x:Static SystemColors.MenuBarBrushKey}}"/>
    </Grid>
</Window>

我遇到编译错误:

Error 1 ImageCanvas is not supported in a Windows Presentation Foundation (WPF) project.

我需要在某处注册我的图像Canvas class吗?

您必须将命名空间引用添加到您的 xaml 代码:

<Window x:Class="FontRendererWPF.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:controls="clr-namespace:FontRendererWPF"
    Title="MyApp" Height="350" Width="525">
<Grid>               
    <controls:ImageCanvas x:Name="canvas" Margin="10,83,7,5" Background="{DynamicResource {x:Static SystemColors.MenuBarBrushKey}}"/>
</Grid>