asbestossupply
asbestossupply

Reputation: 11919

Binding to a ListBox with clickable links

I'm working on my first WPF app and it's pretty cool. Came up against a bit of a brick wall today though.

My app is acting as a web searcher -- visiting search engines and retrieving links. I'd like to display the links in a clickable format. I figured I'd bind the resulting string[] of links to a ListBox and put a Hyperlink in there. After some googling, here's what I came up with:

<ListBox Height="200" ItemsSource="{Binding Path=UrlsFound, Mode=OneWay}" Name="listBox1" Width="727">
    <ListBox.Resources>
        <DataTemplate DataType="String">
            <TextBlock>
                <Hyperlink NavigateUri="{Binding}" RequestNavigate="Hyperlink_RequestNavigate">
                    <TextBlock Text="{Binding}" />
                </Hyperlink>
            </TextBlock>
        </DataTemplate>
    </ListBox.Resources>
</ListBox>

and in the code-behind:

private void Hyperlink_RequestNavigate(object sender, RequestNavigateEventArgs e)
{
    Process.Start(new ProcessStartInfo(e.Uri.AbsoluteUri));
    e.Handled = true;
}

I found that RequestNavigate code in a few places on the web.

So everything's binding fine and the listbox has all the links in it but they are not clickable. I added a breakpoint on RequestNavigate which is not being hit (tried double clicking too) and even tried adding a Click handler too. What am I doing wrong?

Upvotes: 2

Views: 5542

Answers (1)

Andrei Pana
Andrei Pana

Reputation: 4502

I think the problem is that your DataTemplate is not associated in any way with your list items. You should specify the ListBox.ItemTemplate instead of just defining the DataTemplate in the Resources section (it doesn't work like a style without key).

<ListBox Height="200" ItemsSource="{Binding Path=UrlsFound, Mode=OneWay}" Name="listBox1" Width="727">
    <ListBox.ItemTemplate>
        <DataTemplate DataType="String">
            <TextBlock>
                <Hyperlink NavigateUri="{Binding}" RequestNavigate="Hyperlink_RequestNavigate">
                    <TextBlock Text="{Binding}" />
                </Hyperlink>
            </TextBlock>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

Upvotes: 8

Related Questions