WPF: Can the following code be converted from procedural (C #) to declarative (XAML)?
I have the following content in Window
(unneeded sections removed):
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 purely and exclusively for xaml in order to use the WPF DataBinding model.
I think it requires something like an Event trigger and a combination of data binding to the selected item of the itemscontrol or something like that, but I'm not sure how.
Can anyone explain to me how I can convert the above solution to remove the procedural code?
a source to share
If you are using .NET 3.5SP1 you can probably use the new StringFormat binding markup extension to do this. See here for examples of binding to StringFormat.
If .NET 3.5SP1 is not an option, you probably have to create your own ValueConverter. Bind the property value SourceUrl
to the selected artist id and then in your converter return the same string you use in the C # example above.
a source to share
<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}' }" />
a source to share