WPF templating with ObservableCollection

124 views Asked by At

I am working on a local project and I have some issues.

I want to create a template for some results that have 3 strings(where 1 is a hyperlink) and a picture and they come as an ObservableCollection of results type binded to ItemSource.

public TestClass {
  public string Title { get; set; }
  public string Description { get; set; }
  public string Link { get; set; }
  public BitmapImage Thumbnail { get; set; }
}

So, I want to show those results in WPF and I want to use for each item a template and show them in a StackPanel (or ListView).

I tried with ListView but the only thing you can do is select the whole item, but I want also the link to be clickable.

My problem is: how can I create a template to use on each item and then add them in a list that 1 string is clickable?

2

There are 2 answers

0
Ondrej Janacek On BEST ANSWER

As Unflux mentioned, that's a good way to do it. And as for the clickable link, use the Hyperlink control like I did below.

<ItemsControl ItemsSource="{Binding Persons}">
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <Grid>
                <Grid.RowDefinitions>
                    <RowDefinition />
                    <RowDefinition />
                </Grid.RowDefinitions>
                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="Auto" />
                    <ColumnDefinition Width="Auto" />
                    <ColumnDefinition Width="Auto" />
                </Grid.ColumnDefinitions>

                <TextBlock Text="{Binding FirstName}" Grid.Row="0" Grid.Column="0" />
                <TextBlock Text="{Binding LastName}" Grid.Row="0" Grid.Column="1" />
                <TextBlock Text="{Binding Age}" Grid.Row="0" Grid.Column="2" />
                <TextBlock Grid.Row="1" Grid.Column="0" Grid.ColumnSpan="3">
                    <Hyperlink NavigateUri="{Binding BlogAddress}" Click="Hyperlink_OnClick">
                        <TextBlock Text="{Binding BlogAddress}" />
                    </Hyperlink>
                </TextBlock>                        
            </Grid>
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>

and code-behind

private void Hyperlink_OnClick(object sender, RoutedEventArgs e)
{
    var link = sender as Hyperlink;
    Process.Start(link.NavigateUri.ToString());
}

results in

screenshot of demo

You will probably want to style it a bit and maybe apply a different ItemsPanel to really customize the look of your collection. You can also decorate ItemsControl with scrolling.

1
Daniel Gavril On

Thanks with the idea of using ItemsControl with its template. But the Hyperlink I made it work with Click property and giving to it a:

 public ICommand RunHyperlink {
     get {
         return new ActionCommand(this.ButtonClick);
     }
 }

 private void ButtonClick() {
        Process.Start(new ProcessStartInfo(this.Link));
 }