views:

308

answers:

2

I have the following content in a Window (removed unnecessary sections):

XAML:

<Style x:Key="itemstyle" TargetType="{x:Type ContentPresenter}">
        <EventSetter Event="MouseLeftButtonDown" Handler="HandleItemClick"/>
</Style>

<ItemsControl ItemsSource="{Binding ArtistList}" Margin="10" Name="artist_list" ItemContainerStyle="{StaticResource itemstyle}" >
 <ItemsControl.ItemTemplate>
  <DataTemplate>
    <TextBlock Text="{Binding ID}" Foreground="White"/>
  </DataTemplate>
 </ItemsControl.ItemTemplate>
</ItemsControl>

<Controls:RSSViewer x:Name="rssControl" />

C# (Code Behind):

private void HandleItemClick(object sender, MouseButtonEventArgs e)
{
 var selectedArtist = ((ContentPresenter) sender).Content as Artist;
 rssControl.SourceUrl = "http://agnt666laptop:28666/rss.aspx?artistid=" + selectedArtist.ID;
}


Now what I want to do is convert the above mixture of xaml and C# to something that is purely and solely xaml, to take advantage of WPF's DataBinding model.

I think that it requires something like an Event trigger and combination of data binding with the selected item of the itemscontrol element or something like that, but I'm not sure on how to go about it.

Can anyone guide me to how I can convert the above solution to remove the procedural code?

+1  A: 

If you are using .NET 3.5SP1, you can probably use the new StringFormat binding markup extension to do it. See here for examples of binding with StringFormat.

If .NET 3.5SP1 is not an option, then you'll probably have to create your own ValueConverter. Bind the value of the SourceUrl property to the selected artist's ID, and then in your converter return the same string that you're using in the C# sample above.

Andy
A: 
<ItemsControl ItemsSource="{Binding ArtistList}" Margin="10" Name="artist_list" ItemContainerStyle="{StaticResource itemstyle}" >
        <ItemsControl.ItemTemplate>
                <DataTemplate>
                                <TextBlock Text="{Binding ID}" Foreground="White"/>
                </DataTemplate>
        </ItemsControl.ItemTemplate>
</ItemsControl>

<Controls:RSSViewer x:Name="rssControl" SourceUrl="{Binding SelectedItem.ID, ElementName=artist_list, StringFormat= 'http://agnt666laptop:28666/rss.aspx?artistid={0}' }" />
Thomas Levesque
It's not working: System.Windows.Data Error: 4 : Cannot find source for binding with reference 'ElementName=artist_list'. BindingExpression:Path=SelectedItem.ID; DataItem=null; target element is 'RSSViewer' (Name='rssControl'); target property is 'SourceUrl' (type 'String')
Andreas Grech
I don't think that ItemsControl has a SelectedItems property. If you want selection, you'll need to use a ListBox or ListView.
Andy
Andy's right, ItemsControl does not have a SelectedItem property...so we have to do it another way then
Andreas Grech
Yes, that's right... you could use a Selector instead of a ItemsControl
Thomas Levesque