My WPF version of Comicster is coming along leaps and bounds, thanks mostly to the helpful folks over on the MSDN WPF forum.

Today I was toying around with DataTemplates for ListBox items, and I wanted to include a Hyperlink (like a LinkLabel for us WinForms folks) in each item. My template looks something like this:

    <DataTemplate x:Key="PublisherItemTemplate">
        <
StackPanel Margin="0,4,0,4">
            <
TextBlock Text="{Binding Name}" Style="{StaticResource ListItemHeaderStyle}" />
            <
TextBlock Style="{StaticResource ListItemDetailStyle}">
                <
Hyperlink NavigateUri="{Binding Uri}">
                    <
TextBlock Text="{Binding Uri}"/>
                </
Hyperlink>
            </
TextBlock>
        </
StackPanel>
    </
DataTemplate>

So as you can see, I'm showing the name of the publisher, and then, underneath it, a link to the publisher's home page (in a property called "Uri").

Problem is ... Hyperlinks by themselves don't really do anything. If you want them to pop open a web browser with the address specified, you need to handle their "RequestNavigating" event and start the process manually. This is all very well, but my template isn't stored inside the main window's XAML file - it's tucked safely away in its own XAML file. That means that it has no "code-behind" in which to handle the event in question.

So what to do? How can I tell the Hyperlink what to do when it's clicked?

Well, it turns out that you can handle the event up in the ListBox itself! Like this:

   <ListBox Name="publisherList"
                 ItemTemplate="{StaticResource PublisherItemTemplate}"
                 ItemsSource="{Binding Publishers}"
                 Hyperlink.RequestNavigate="OpenUri" />

See? I've actually told the ListBox that any time a Hyperlink inside it is clicked, call the "OpenUri" method in my window's code-behind.

This is something I never would have considered trying, and it really makes me wonder what else might be possible using this sort of construct.

So there you go - my WPF lesson learned for today.