Problem: I need to display a feed from a certain source in a WPF ListBox.
Approach: Set the item source of the ListBox to a dependency property. As the property changes, the items in the ListBox will also change.
Solution:
1. Create a dependency property and its wrapper CLR property.
/// <summary>
/// The Feed dependency property.
/// </summary>
public static readonly DependencyProperty FeedProperty = DependencyProperty.Register("Feed", typeof(SyndicationFeed), typeof(FeedViewer));
/// <summary>
/// Gets or sets the feed.
/// </summary>
/// <value>The syndication feed.</value>
public SyndicationFeed Feed
{
get { return (SyndicationFeed)GetValue(FeedProperty); }
set { SetValue(FeedProperty, value); }
}
Note that FeedViewer is the user control containing the ListBox.
2. Bind the ListBox item source to the property.
There are two ways (well, at least, I think) to accomplish this.
2.1 XAML
<UserControl x:Class="Controls.Wpf.FeedViewer" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
x:Name="usrFeedViewer">
<Grid>
<ListBox x:Name="uxFeedListBox"
ItemsSource="{Binding ElementName=usrFeedViewer, Path=Feed.Items}" HorizontalContentAlignment="Stretch"
Grid.Row="1" Margin="12,0,12,12" />
</Grid>
</UserControl>Note that the ItemSource accepts IEnumerable. Therefore, we assign the feed items for it instead of just Feed.
2.2 Code Behind
For this approach, we are to create a PropertyChangedCallback event to handle when the Feed property is changed.
There is no need to set the ItemSource property in XAML for the ListBox.
The dependency property will be changed to:
/// The Feed dependency property.
/// </summary>
public static readonly DependencyProperty FeedProperty = DependencyProperty.Register("Feed", typeof(SyndicationFeed), typeof(FeedViewer), new FrameworkPropertyMetadata(null, new PropertyChangedCallback(OnFeedChanged)));
Now we define the event named OnFeedChanged:
/// <summary>
/// Called when [feed changed].
/// </summary>
/// <param name="sender">The sender.</param>
/// <param name="e">The <see cref="System.Windows.DependencyPropertyChangedEventArgs"/> instance containing the event data.</param>
private static void OnFeedChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
{
var feedViewer = (FeedViewer)sender;
var newValue = (SyndicationFeed)e.NewValue;
feedViewer.uxFeedListBox.ItemsSource = null;
feedViewer.uxFeedListBox.ItemsSource = newValue.Items;
}
Now when you set/change the Feed property for this control in your application, the ListBox will show you corresponding feed :)