C# 在WPF中将画布的派生类添加到窗口时出现问题
我是WPF的新手,我正在学习《职业WPF C#2010》。我想创建一个自定义的canvas派生类,然后将其添加到主窗口中,但无法将其添加到主窗口中 我所做的是创建了一个名为DrawingCanvas的新类(添加了DrawingCanvas.c#file),并声明如下:C# 在WPF中将画布的派生类添加到窗口时出现问题,c#,.net,wpf,xaml,C#,.net,Wpf,Xaml,我是WPF的新手,我正在学习《职业WPF C#2010》。我想创建一个自定义的canvas派生类,然后将其添加到主窗口中,但无法将其添加到主窗口中 我所做的是创建了一个名为DrawingCanvas的新类(添加了DrawingCanvas.c#file),并声明如下: <Window x:Class="CustomDrawingCanvas.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/present
<Window x:Class="CustomDrawingCanvas.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Grid>
<StackPanel Name="spanel">
<local:DrawingCanvas x:Name="drawingSurface" Background="White" ClipToBounds="True"
MouseLeftButtonDown="drawingSurface_MouseLeftButtonDown"
MouseLeftButtonUp="drawingSurface_MouseLeftButtonUp"
MouseMove="drawingSurface_MouseMove" />
</StackPanel>
</Grid>
</Window>
public void AddDrawingSurface()
{
drawingSurface = new DrawingCanvas();
drawingSurface.Background = new SolidColorBrush(Colors.AliceBlue);
drawingSurface.ClipToBounds = true;
Button button = new Button();
button.Content = "A button";
//spanel.Children.Add(button);
spanel.Children.Add(drawingSurface);
}
类别的定义:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Media;
using System.Windows.Controls;
namespace CustomDrawingCanvas
{
public class DrawingCanvas : Canvas
{
private List<Visual> visuals = new List<Visual>();
protected override int VisualChildrenCount
{
get
{
return visuals.Count;
}
}
protected override Visual GetVisualChild(int index)
{
return visuals[index];
}
public void AddVisual(Visual visual)
{
visuals.Add(visual);
base.AddVisualChild(visual);
base.AddLogicalChild(visual);
}
public void DeleteVisual(Visual visual)
{
visuals.Remove(visual);
base.RemoveVisualChild(visual);
base.RemoveLogicalChild(visual);
}
}
}
我在InitializeComponent()之后调用这个函数
添加按钮,但不添加堆栈面板。请解释一下我缺少的东西是什么,我尝试过谷歌搜索,并找到了许多通过代码添加自定义元素的方法,方法大体相同,适用于其他元素,但不适用于DrawingCanvas:Canvas类。您需要在Windows类标题中声明您的本地别名,即
<Window x:Class="CustomDrawingCanvas.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="The namespace of your custom control here"
Title="MainWindow" Height="350" Width="525">
<Window x:Class="CustomDrawingCanvas.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="The namespace of your custom control here"
Title="MainWindow" Height="350" Width="525">