Wjdavis5
Wjdavis5

Reputation: 4151

WPF Binding in Xaml

Similar questions galore for this and I just cant seem to figure out what is going on.

I'm short bus struggling to get my ListView populated, being bound to an ObservableCollection...

Code:

<controls:MetroWindow
       ...blah...
        Title="MainWindow" x:Name="Main" DataContext="{Binding ElementName=Main}"   

<ListBox Grid.Row="0" x:Name="FileNames" HorizontalAlignment="Left" Height="221" Margin="10,62,0,0" VerticalAlignment="Top" Width="258" 
             SelectionChanged="FileNames_SelectionChanged" BorderThickness="2"
             ItemsSource="{Binding Reports, UpdateSourceTrigger=PropertyChanged}">
    <ListBox.ItemTemplate>
            <DataTemplate>
                <Label CacheMode="{Binding Path=FileName,UpdateSourceTrigger=PropertyChanged}"></Label>
            </DataTemplate>
    </ListBox.ItemTemplate>    

    </ListBox>


//Code Behind

public ObservableCollection<ReportsModel> Reports { get; set; }


Reports = setReports();

ReportsModel impls INotifyPropertyChanged

public sealed class ReportsModel : INotifyPropertyChanged

I can step in and see that Reports gets populated fine and that the filename field is also populated on each report but nothing is showing up in my ListBox.

Any help would be very appreciated.

Upvotes: 1

Views: 70

Answers (2)

Breeze
Breeze

Reputation: 2058

You should enhance your code with everything around PropertyChanged. That means:

Main should implement INotifyPropertyChanged
Notify the UI when the Source changes, for example

if (PropertyChanged != null)
{
    PropertyChanged(this, new PropertyChangedEventArgs("Reports"));
}

Edit after slightly changed question: the Reports valiue should be get/st in the following way to avoid problems:

private ObservableCollection<ReportsModel> _Reports;
public ObservableCollection<ReportsModel> Reports
{
    get { return _Reports; }
    set
    { 
        _Reports = value;
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs("Reports"));
        }
    }
}

I guess Main has to implement INotifyPropertyChanged too.

Upvotes: 1

ΩmegaMan
ΩmegaMan

Reputation: 31721

The reference holding the ObservableCollection<ReportsModel> named Reports can't have a plain getter/setter. You need to implement INotifyPropertyChange on the Main class and change Reports to signal a property change like this

private ObservableCollection<ReportsModel> _reports;

public ObservableCollection<ReportsModel> Reports 
{ 
   get { return _reports; }
   set
     {
         _reports = value;
         PropertyChanged("Reports");
     } 
}

ReportsModel impls INotifyPropertyChanged

The data held has nothing to do with the collection's property Reports binding change notification.

Upvotes: 3

Related Questions