Harsh
Harsh

Reputation: 3751

Binding class object to listview in wpf

I have created a user control in wpf which consists of a textbox and a listview. Now, I want to bind a class object to the list view from the form where I will use this control. So, basically I want to dynamically set the binding for the listview.

This might be simple but I am new to wpf which is making this a giant task for me. Please suggest a solution for this.

Upvotes: 2

Views: 9996

Answers (1)

EvAlex
EvAlex

Reputation: 2938

You need to bind your ListView's ItemsSource property to a collection of your class instances (I recommend using ObservableCollection for this). You can place the collection into ListView's DataContext, for example. Then the binding will be just

<ListView ItemsSource={Binding} .../>

It is more useful to create a class to contain this collection along with any other objects that your UserControl may require and pass the instance of this class to UserControl's DataContext. This refers to MVVM pattern.

EDIT

You can set DataContext either in code-behind or in xaml. Let's say we have a class with the collection:

public class ViewModel
{
    public ViewModel()
    {
        Products = new ObservableCollection<Product>()
        {
            new Product("book"),
            new Product("chair"),
            new Product("table"),
            new Product("bookshelf"),
        }
    }

    ObservableCollection<Product> Products { get; set; }
}

Here's how to set UserControl's DataContext in code:

userControl.DataContext = new ViewModel();

where userControl is an instance of your UserControl.

Here's how to do in in xaml:

<UserControl ...
             xmlns:vm="namespace_containing_class_ViewModel">
    <UserControl.DataContext>   
        <!-- Following line instantiates the ViewModel class and calls its parameterless constructor -->
        <vm:ViewModel />
    </UserControl.DataContext>

    ...
    <ListView ItemsSource="{Binding Products}"/>
    ...
</UserControl>

Both variants do exactly the same thing. Note that ItemsSource="{Binding Products}" means that the Binding.Path property is set to "Products" and this path will be searched for in ListView's DataContext. If ListView's DataContext is not explicitly set (as in the mentioned above case) it's DataContext is the same as its Parent's DataContext. If the parent's DataContext is not set - then it's the same as parent's parent's DataContext and so on. So in this case ListView's DataContext is the same as UserControl's DataContext and is a ViewModel class instance, that containes collection of Products. Ta-da! :)

Upvotes: 6

Related Questions