Martin
Martin

Reputation: 1947

WPF binding ObservableCollection to ListBox

I'm trying to bind ObservableCollection to ListBox. Output from debug doesn't show any binding errors, yet for some reason it doesn't work.

xaml:

<Window
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:nwsfeed"
x:Class="nwsfeed.MainWindow"
DataContext="{Binding RelativeSource={RelativeSource Self}}"
x:Name="Window">

    <ListBox x:Name="listBoxChannels" 
    ItemsSource="{Binding ElementName=Window, Path=App.ActiveProfile.Feeds}"
    DisplayMemberPath="Title"/>

</Window>

code:

public partial class MainWindow : Window {
    public NwsfeedApp App { get; set; }
    // ..
}

public sealed class NwsfeedApp {
    public UserProfile ActiveProfile { get; set; }
    //..
}

public class UserProfile {
    private ObservableCollection<RSSFeed> feeds;
    public ObservableCollection<RSSFeed> Feeds { get { return feeds; } }
    //..
}

edit: The problem is that when I have ObservableCollection as a public property of a MainWindow and I bind it like this, it works:

ItemsSource="{Binding ElementName=Window, Path=Items, Mode=OneWay}" 

But when I do this, it doesn't:

ItemsSource="{Binding ElementName=Window, Path=App.ActiveProfile.Feeds, Mode=OneWay}" 

edit2 I've implemented INotifyPropertyChanged in App, ActiveProfile and Feeds properties. ListBox still doesn't reflect the changes on collection, unless i call .Items.Refresh() on it.

Any suggestions? Thanks.

Upvotes: 2

Views: 1236

Answers (2)

Louis Kottmann
Louis Kottmann

Reputation: 16618

With lack of information, here's a shot in the dark:

You're trying to access App which is a static application property that isn't an instantiated variable within the code-behind of your window. The rest of the property path in your binding isn't evaluated because App cannot be found.

You probably want this:

ItemsSource="{x:Static local:App.ActiveProfile.Feeds}"

For the missing output, try Tools->Options->Debugging->Output window->WPF Trace Settings there you have options to see more or less information on the available WPF traces.

HTH,

Bab.

Upvotes: 0

LPL
LPL

Reputation: 17063

Implement INotifyPropertyChanged on your classes.

Upvotes: 1

Related Questions