Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF Collections and Databinding

I am new to WPF and trying to wrap my head around WPF's framework, what it does and does not do for you.

To clarify this, I would like to know what is the difference between this:

public List<MyCustomObject> MyCustomObjects
{
    get { return (List<MyCustomObject>)GetValue(MyCustomObjectsProperty); }
    set { SetValue(MyCustomObjectsProperty, value); }
}

public static readonly DependencyProperty MyCustomObjectsProperty =
    DependencyProperty.Register("MyCustomObjects", typeof(List<MyCustomObject>),
    typeof(Main), new UIPropertyMetadata(new List<MyCustomObject>()));



and this:

public ObservableCollection<MyCustomObject> MyCustomObjects { get; set; }

public Main ()
{
    MyCustomObjects = new ObservableCollection<<MyCustomObject>();
}
like image 702
Vaccano Avatar asked Jul 06 '26 13:07

Vaccano


1 Answers

Ok, we must put some order into things, there's a few concepts mixed in together here.

First of all, you're asking what the difference is between a field-backed property and a dependency property. Google would be your best friend, however I recommend this blog post by WPF's vanguard Josh Smith: Overview of dependency properties in WPF

In short: dependency properties support the richness that is WPF: Styling, animation, binding, metadata, and more.

Secondly, you're asking what the difference is between a List and an ObservableCollection. Well the latter provides change notifications (in the forms of events) on any change to the collection (addition, removal, change of order, clearing, etc.), and the former does not. You can read more about that here: The ObservableCollection Class

In short: ObservableCollection provides change notifications which are required for the UI to automatically reflect changes in the view model.

like image 168
Aviad P. Avatar answered Jul 08 '26 02:07

Aviad P.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!