在自定义控件中没有来自Rectangle对象的事件
问题描述:
嗨
我尝试使用2D对象制作自定义控件.问题是我没有从2D对象获得事件.当我将以下代码中的Rectangle替换为Button时,将发送事件.
我忘记了什么?
非常感谢!
文件RectangleButton.cs:
Hy
I try to make a Custom Control with 2D Objects. The Problem is, that i didn’t get events form 2D Object. When i replace Rectangle in the following code with a Button, the event will be sent.
What does i forgot?
Many Thanks!
File RectangleButton.cs:
public class RectangleButton : Control
{
private Rectangle _buttonWrite;
static RectangleButton()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(RectangleButton), new FrameworkPropertyMetadata(typeof(RectangleButton)));
}
public override void OnApplyTemplate()
{
base.OnApplyTemplate();
_buttonWrite = new Rectangle();
_buttonWrite = this.GetTemplateChild("myRectangle") as Rectangle;
_buttonWrite.AddHandler(Rectangle.MouseDownEvent, new MouseButtonEventHandler(ButtonWrite_MouseLeftButtonDown), true);
}
void ButtonWrite_MouseLeftButtonDown(object sender, MouseEventArgs e)
{
MessageBox.Show("MouseLeftButtonDown Event!!");
}
}
Generic.xaml文件:
<resourcedictionary>
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:RectangleEvent">
<Style TargetType="{x:Type local:RectangleButton}">
<setter property="Template">
<setter.value>
<controltemplate targettype="{x:Type local:RectangleButton}">
<border removed="{TemplateBinding Background}">
BorderBrush="{TemplateBinding BorderBrush}"
BorderThickness="{TemplateBinding BorderThickness}">
<grid>
<rectangle x:name="myRectangle" xmlns:x="#unknown" />
</grid>
</border>
</controltemplate>
</setter.value>
</setter>
</Style>
</resourcedictionary>
MainWindow.xaml文件:
<window x:class="RectangleEvent.MainWindow" xmlns:x="#unknown">
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525" xmlns:my="clr-namespace:RectangleEvent">
<grid>
<my:rectanglebutton horizontalalignment="Left" x:name="rectangleButton1" verticalalignment="Top" height="141" width="162" removed="#FFF81010" xmlns:my="#unknown" />
</grid>
</window>
答
矩形没有背景,因此不会受到测试.
试试
The Rectangle has no background so doesn''t get hittested.
Try
<Rectangle x:Name="myRectangle" Fill="Transparent" />
我不敢相信我找到一个LOL * facepalm *
I can''t believe how long it took me to find that one LOL *facepalm*