This is a migrated thread and some comments may be shown as answers.

Data Binding to ObservableCollection in ViewModel

1 Answer 341 Views
GridView
This is a migrated thread and some comments may be shown as answers.
Tony
Top achievements
Rank 1
Tony asked on 04 Feb 2010, 04:56 AM
Hello,

In my view model, LogEntries is declared as this:

    public class LogServiceViewModel : INotifyPropertyChanged, IDisposable        
    {        
        public ObservableCollection<CmsLogEntry> LogEntries = new ObservableCollection<CmsLogEntry>();     
    } 

I set the DataContext to my view model in the window constructor. All other data binding (aside from the grid) works at this point.

When I create a binding to LogEntries in xaml it doesn't work:

<telerik:RadGridView Name="gridView" ItemsSource="{Binding LogEntries}" AutoGenerateColumns="True"

But when I create a method wrapper to return the collection and bind in the window constructor code behind, it does:

Collection wrapper method
    public class LogServiceViewModel : INotifyPropertyChanged, IDisposable        
    {        
        public ObservableCollection<CmsLogEntry> LogEntries = new ObservableCollection<CmsLogEntry>();     
    
        public ObservableCollection<CmsLogEntry> GetLogEntries()     
        {     
                return LogEntries;     
        }     
    } 

Binding (XAML):

<telerik:RadGridView Name="gridView" AutoGenerateColumns="True"

Binding (Window constructor):

        public MainWindow()  
        {  
            _logServiceModel = new LogServiceModel();  
            _logServiceViewModel = new LogServiceViewModel(_logServiceModel);  
            DataContext = _logServiceViewModel;  
 
            gridView.ItemsSource = _logServiceViewModel.GetLogEntries();  
        }  
 

I really was hoping to avoid polluting the code behind as much as possible to create bindings to my view model. I've looked at the docs and don't see an example of this, but am surprised to find that this isn't supported. I must be doing something wrong. Anyone have any ideas? Thanks!

Tony

1 Answer, 1 is accepted

Sort by
0
Tony
Top achievements
Rank 1
answered on 04 Feb 2010, 05:05 AM
Boy do I feel silly for posting. I added:

<telerik:RadGridView Name="gridView" ItemsSource="{Binding LogEntries, PresentationTraceSources.TraceLevel=High}" AutoGenerateColumns="True">  
 

And spotted the problem right away. I was binding to a field instead of a property. Doh!

This works correctly, as one would expect.

        private ObservableCollection<CmsLogEntry> _logEntries = new ObservableCollection<CmsLogEntry>();  
 
        public ObservableCollection<CmsLogEntry> LogEntries  
        {  
            get  
            {  
                return _logEntries;  
            }  
        }  
 

Sorry for the false alarm!  :-p

Tags
GridView
Asked by
Tony
Top achievements
Rank 1
Answers by
Tony
Top achievements
Rank 1
Share this question
or