I am developing a diagramming project within C# using WPF. I based the
visual representation off a tutorial from CodeProject <a
href=http://www.codeproject.com/KB/WPF/WPFDiagramDesigner_Part4.aspx">WPF
Diagram Designer</a>. I've added most of the extensions that I need for the
solution but I'm new to WPF and having trouble getting RoutedEvents to work
correctly.
I have a canvas object which has several designerItems on it. The
DesignerItem class has a RoutedEvent called NewDesignerItemEvent which is
fired whenever a new item is created:
<code>
/// <summary>
/// Notify any listeners that a new Designer Item has been created.
/// </summary>
public static readonly RoutedEvent NewDesignerItemEvent =
EventManager.RegisterRoutedEvent("NewDesignerItem" ,
RoutingStrategy.Bubble,
typeof(RoutedEventHandler),
typeof(DesignerItem));
public event RoutedEventHandler NewDesignerItem
{
add { AddHandler(NewDesignerItemEvent, value); }
remove { RemoveHandler(NewDesignerItemEvent, value); }
}
/// <summary>
/// Fires the NewDesignerItemEvent with a reference to this instance
/// of the DesignerItem class
/// </summary>
private void NotifyNewDesignerItem()
{
RoutedEventArgs e = new
RoutedEventArgs(DesignerItem.NewDesignerItemEvent, this);
RaiseEvent(e);
}
</code>
Within my XAML I have added an EventHandler that should catch all
NewDesignerItem events that are bubbling up:
<code>
<s:DesignerCanvas
Focusable="true"
x:Name="MyDesigner"
s:DesignerItem.NewDesignerItem="MyDesigner_NewDesi gnerItem"
Background="{StaticResource
WindowBackgroundBrush}"
Margin="10" FocusVisualStyle="{x:Null}"
ContextMenu="{StaticResource
DesignerCanvasContextMenu}"/>
</code>
The behavior I am expecting is that whenever the NewDesignerItem event is
fired for a child within the DesignerCanvas object "MyDesigner" that event
will be "bubled up" to my event handler. However, nothing happens! I can
step through the creation of the DesignerItem and verify that my RoutedEvent
is being called but the Handler never gets it.
I was able to get the event handler to fire by using
EventManager.RegisterClassHandler() within my Window constructor.
Unfortunately, this implementation doesn't meet my goals because I will
eventually have dozens of Canvas objects and I only want to handle the event
on the canvas that "owns" the newly added DesignerItem.
I did a sanity test by replacing my NewDesignerItem event with the
ButtonBase.Click event and trapping that. This implementation works fine and
my EventHandler is called as expected for all buttons contained in my
DesignerCanvas.
<code>
<s:DesignerCanvas
Focusable="true"
x:Name="MyDesigner"
ButtonBase.Click="MyDesignerButton_Click"
Background="{StaticResource
WindowBackgroundBrush}"
Margin="10" FocusVisualStyle="{x:Null}"
ContextMenu="{StaticResource
DesignerCanvasContextMenu}">
</s:DesignerCanvas>
</code>
Thanks in advance!
I'm using Visual Studio 2008 Professional with .NET Framework 3.5 SP1