2
votes

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.

2
"Doesn't work" is a bit vague, what do you see and what did you expect instead? - Louis Kottmann
You should specify that the binding is oneway, seeing as the property doesn't have a set. Not sure if that will help, but I consider it a good practice. - Jason Ridge
No ListBox items are displayed even though there are items in collection which it is bind to. - Martin

2 Answers

1
votes

Implement INotifyPropertyChanged on your classes.

0
votes

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.