为什么我只能在设置背景颜色后在Canvas上绘制点?

时间:2012-08-24 18:11:28

标签: c# wpf xaml

我有一个简单的程序,它实现this question中讨论的代码来跟踪鼠标移动。但是,似乎只有在设置了Canvas控件的背景颜色时才会触发事件。

XAML(背景颜色设置):

<Window x:Class="SimplePaint.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="501" Width="784">
    <Grid>
        <Canvas Height="402" HorizontalAlignment="Left" Margin="12,12,0,0" Name="PaintCanvas" VerticalAlignment="Top" Width="738" MouseDown="PaintCanvas_MouseDown" MouseMove="PaintCanvas_MouseMove" MouseUp="PaintCanvas_MouseUp" Background="#FFDEF4FF">
            <Polyline x:Name="polyline" Stroke="Black" StrokeThickness="3"/>
        </Canvas>
    </Grid>
</Window>

C#:

private bool drawing = false;

private void PaintCanvas_MouseDown(object sender, MouseButtonEventArgs e)
{
    this.drawing = true;
}

private void PaintCanvas_MouseMove(object sender, MouseEventArgs e)
{
   if (this.drawing)
        polyline.Points.Add(e.GetPosition(this.PaintCanvas));
}

private void PaintCanvas_MouseUp(object sender, MouseButtonEventArgs e)
{
    this.drawing = false;
}

此代码有效。但是,如果我从XAML中删除Background="#FFDEF4FF",则在使用该程序时不会发生任何事情。在事件处理程序中设置断点表明它们不会触发。

1 个答案:

答案 0 :(得分:2)

你有没有为背景尝试过“透明”....否则你的背景= null(即没有背景)......而且WPF的HitTesting逻辑没有碰到你的对象。

有关解释,请参阅此处: