Farax
Farax

Reputation: 1477

Passing Generic lists to a WPF usercontrol

I want to create a usercontrol that takes lists of different objects. These objects would be assigned to the control at design time. Now I want to be able to use linq to object to sort this list inside the usercontrol. Can anyone give me any ideas as how to go about it?

Upvotes: 0

Views: 1799

Answers (1)

Aviad P.
Aviad P.

Reputation: 32639

Add a DependencyProperty of type ObservableCollection<T> to your user control class (call it MyItemsSource for example). In your containing XAML, bind that property to your Linq collection, and inside your user control, bind your ListBox (or other ItemsControl) to the property as follows:

{Binding 
    RelativeSource={RelativeSource 
                        Mode=FindAncester, 
                        AncestorType=UserControl}, 
    Path=MyItemsSource}

Alternatively, you can set the Name property inside the user control on the top level element (the UserControl element) to for example MyUserControl, and bind against an ElementName instead of a RelativeSource as such:

{Binding ElementName=MyUserControl, Path=MyItemsSource}

Upvotes: 4

Related Questions