我对 c# WPF routedevent 有问题。此代码工作正常:
MyLabel myLabel = new MyLabel();//MyOwn component
myLabel.Oma += new RoutedEventHandler(myLabel_Click);
GameArea.Children.Add(mylabel);//GameArea is UniformGrid
但是当我将 myLabel 放在 ToggleButton 的内容中时,routedeventhandler(myLabel_Click) 没有捕获 Oma 事件(我调试了它):
MyLabel myLabel = new MyLabel();//MyOwn component
myLabel.Oma += new RoutedEventHandler(myLabel_Click);
System.Windows.Controls.Primitives.ToggleButton box = new System.Windows.Controls.Primitives.ToggleButton();
box.Content = myLabel;
GameArea.Children.Add(box);//GameArea is UniformGrid
那么为什么 ToggleButton 会阻止我的 routedevent 呢?
编辑:代码工作正常,但当我将 myLabel 放入 ToggleButton 的内容时,它会产生麻烦。
MyLabel 中的 OmaEvent 看起来像这样:
public static readonly RoutedEvent OmaEvent =
EventManager.RegisterRoutedEvent("Oma", RoutingStrategy.Bubble,
typeof(RoutedEventHandler), typeof(MyLabel));
public event RoutedEventHandler Oma
{
add { AddHandler(OmaEvent, value); }
remove { RemoveHandler(OmaEvent, value); }
}
protected override void OnMouseDown(MouseButtonEventArgs e)
{
base.OnMouseDown(e);
CaptureMouse();
}
protected override void OnMouseUp(MouseButtonEventArgs e)
{
base.OnMouseUp(e);
if (IsMouseCaptured)
{
ReleaseMouseCapture();
if (IsMouseOver)
RaiseEvent(new RoutedEventArgs(OmaEvent, this));
}
}
如果我把它放在 ToggleButton 中,OmaEvent 永远不会引发。如果我不把它放在 ToggleButton 中,它就可以工作。