【发布时间】:2011-11-02 01:00:36
【问题描述】:
您好,我有以下代码,我正在使用按钮模板在画布上绘制一个按钮,当我单击该按钮时,我希望显示一条消息,但即使我按下鼠标,它也不会显示按钮上的事件仍然无法识别。
private void Canvas_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
Button r = e.Source as Button;
if (r != null)
MessageBox.Show(r.ToString());
Point mousePoint = Mouse.GetPosition(mainCanvas);
Button button1 = new Button();
button1.Template = (ControlTemplate)this.FindResource("nodeTemplate");
Canvas.SetTop(button1, mousePoint.Y);
Canvas.SetLeft(button1, mousePoint.X);
mainCanvas.Children.Add(button1);
}
}
<Window.Resources>
<ControlTemplate x:Key="nodeTemplate" TargetType="Button">
<Grid>
<Ellipse x:Name="outerCircle" Fill="Red" Height="50" Width="50"/>
<Ellipse x:Name="innerCircle" Fill="Green" RenderTransformOrigin=".5,.5">
<Ellipse.RenderTransform>
<ScaleTransform ScaleX=".9" ScaleY=".9"/>
</Ellipse.RenderTransform>
</Ellipse>
</Grid>
</ControlTemplate>
</Window.Resources>
<DockPanel>
<Canvas x:Name="mainCanvas" Background="Transparent" MouseLeftButtonDown="Canvas_MouseLeftButtonDown">
</Canvas>
</DockPanel>
【问题讨论】:
-
@Meleak :我想我误删了Meleak的答案,你能重新发布吗?
-
呵呵不是,是我删的。我认为这是常见的 Background is null 问题,但在仔细查看您的代码后,我注意到您已经拥有
Background="Transparent"所以答案没用:) -
@Meleak :背景对于画布来说是透明的,但是按钮有一个填充并且没有背景属性,你知道背景和填充有什么区别吗?但是 Ellipse 没有 Background 属性。
-
Fill 是在 Shape 上定义的,因此从
Shape继承的每个控件都有一个Fill属性。形状通常没有Foreground属性,因此它不是真正的Background,因为形状本身不会在其上绘制任何内容,它只是填充:)Background定义在Control和TextElement(也许还有其他地方)