eYe
eYe

Reputation: 1733

DataContext scope during binding

I have a View A that has a UserControl U containing its own UserControl UChild.

When I set the DataContext of A, will UChild get the DataContext of A using direct binding to its grandparent's property i.e. { Binding PropertyFromA } within UChild?

I am trying to achieve this but looks like grandchild in my case does not get the DataContext.

Edit:

Some code I use:

My binding happens inside the VM, where BookList is an ObservableCollection that gets filled with Books:

    /// <summary>
    /// 
    /// </summary>
    public bool FillBooksCtrlList()
    {
        List<Book> list = DBHelper.GetRecipes();
        if (list == null)
        {
            return false;
        }
        else
        {
            BookList = new ObservableCollection<Book>(list);
            foreach (Book book in BookList)
            {
                BookCtrlList.Add(new BookCtrl { DataContext = book, Margin = new Thickness(0, 10, 10, 0) });
            }
            return true;
        }
    }

In short, I am creating an instance of BookCtrl inside BookPanelCtrl that belongs to the MainView.

Maybe the way I bind is the problem?

Upvotes: 0

Views: 497

Answers (1)

venerik
venerik

Reputation: 5904

I think you want something like this. In your ViewModel you have an ObservableCollection containing Books:

public class SomeViewModel {
    private ObservableCOllection<Book> _books;
    public ObservableCollection<Book> Books 
    {
        get
        {
            return _books;
        }
        set
        {
            _books = value;
            RaisePropertyChanged("Books");
        }
    }
}

public bool FillBooksCtrlList()
{
    List<Book> list = DBHelper.GetRecipes();
    if (list == null)
    {
        return false;
    }
    else
    {
        Books = new ObservableCollection<Book>(list);
        return true;
    }
}

Then, in your View you could have something like:

<UserControl DataContext="SomeViewModel">
    <ListBox ItemsSource="{Binding Books}">
        <ListBox.ItemTemplate>
            <DataTemplate>
                <TextBox Text="{Binding Title}"/>
            </DataTemplate>
        </ListBox.ItemTemplate>
    </ListBox>
</UserControl>

This way the UserControl is bound to the ViewModel, the ListBox is bound to your list of Books and each item in the ListBox is bound to the Title property of a book (I'm guessing books have a title).

Hope this helps.

Upvotes: 1

Related Questions