Question

Recently I have found out that in my binding, the second simplified method is working just as good as the second one. Since I have always done it using the first, I want to know what could be the reason to chose one or the other.

Public method with a dummy Private variable

public ObservableCollection<MyDeviceInfo> DiscoveredDevicesList
{
    get
    {
        return _DiscoveredDevicesList;
    }
    set
    {
        _DiscoveredDevicesList = value;
        OnPropertyChanged("DiscoveredDevicesList");
    }
}
private ObservableCollection<MyDeviceInfo> _DiscoveredDevicesList;

Auto-Implemented Properties

public ObservableCollection<MyDeviceInfo> DiscoveredDevicesList { get; set; }
Was it helpful?

Solution

It refers primarily to the ObservableCollection<T> properties. The Public method with a dummy Private variable need to specify the DataContext via XAML, for example:

ObservableCollection<T>

public class ViewModel : NotificationObject
{
    private ObservableCollection<Person> _myCollection;

    public ObservableCollection<Person> MyCollection
    {
       get
       {
           return _myCollection;
       }

       set
       {
           _myCollection = value;
           NotifyPropertyChanged("MyCollection");
       }
    }
}

XAML

<!-- Set the DataContext in XAML -->
<Window.DataContext>
    <local:ViewModel />
</Window.DataContext>

<Grid>
    <ListBox ItemsSource="{Binding Path=MyCollection}" /> <!-- Or any other control -->
</Grid>

Work with collection in code-behind like this:

ViewModel MyViewModel = this.DataContext as ViewModel;

MyViewModel.MyCollection = new ObservableCollection<Person>();

MyViewModel.MyCollection.Add(new Person()
{
    Age = 22,
    Name = "Nick",
});

In this case, if the collection would have been with automatic property:

public ObservableCollection<Person> MyCollection
{
    get;
    set;
}

Then Binding would not work, namely the it would not update the property collection. But, if you set the DataContext in code-behind:

this.DataContext = MyViewModel;

The Binding will work with automatic property.

OTHER TIPS

Using the auto-implemented property, if you set the DiscoveredDevicesList property to a entirely new ObservableCollection, your view will have no way of knowing. However, if all you are doing is adding/removing/reordering items in a single instance of the ObservableCollection, then this will work fine because the view is also binding to the INotifyCollectionChanged interface (which is implemented by ObservableCollection) on DiscoveredDevicesList.

You can bind auto-properties but any changes you make to the property from code won't show up in the UI. In general any object being used for data binding should include change notification and so should not use auto-properties.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top