Kent Fonager
Kent Fonager

Reputation: 3

How to bind Layout to ViewModel from code?

I'm trying to bind items to a StackLayout via this documentation: https://learn.microsoft.com/en-us/xamarin/xamarin-forms/user-interface/layouts/bindable-layouts

I don't use XAML, so I obviously need to bind from inside my code, the documentation shows how to do it this way:

IEnumerable<string> items = ...;
var stack = new StackLayout();
BindableLayout.SetItemsSource(stack, items);

But I need to reference a property from withing my ViewModel, set earlier via the View's BindingContext. Could someone please help me doing this?

Something ala (pseudocode):

var stack = new StackLayout() { ... };
stack.SetBinding(StackLayout.ItemsSource, "Items")

I dont want my controller to know anything about the actual viewModel, and the way its suggested, I need to use it in a typed matter, where I should know the ViewModel.

Below is an example of what I'm trying to accomplish. Please note I use NO XAML at all! Write all my UI in code:

using System;
using System.Collections.Generic;
using Xamarin.Forms;

namespace LayoutTest
{
    public class MyPage : ContentPage
    {
        public MyPage()
        {
            BindingContext = new MyViewModel();

            var layout = new StackLayout();

            BindableLayout.SetItemsSource(layout, "?????");
            BindableLayout.SetItemTemplate(layout, new DataTemplate(() =>
            {
                var lbl = new Label();
                lbl.SetBinding(Label.TextProperty, "Name");

                return lbl;
            }));

            Content = layout;
        }
    }

    public class MyViewModel
    {
        List<Item> Items { get; set; }
        public MyViewModel()
        {
            Items = new List<Item>();
            Items.Add(new Item { Name = "Kent" });
            Items.Add(new Item { Name = "Tony" });
            Items.Add(new Item { Name = "Allan" });
        }
    }

    public class Item
    {
        public string Name { get; set; }
    }
}

Dont know what to write in this line:

BindableLayout.SetItemsSource(layout, "?????");

It only take a collection as a property, but then I need to know about the ViewModel, but I dont want that.

What to do?

Upvotes: 0

Views: 700

Answers (2)

David Ortinau
David Ortinau

Reputation: 271

layout.SetBinding(BindableLayout.ItemsSourceProperty, new Binding("Items”));

Do that instead of the BindableLayout.SetItemsSource that you have now. The binding will use the existing binding context when setting this.

Upvotes: 4

maciejgos
maciejgos

Reputation: 103

@KenFonager from code behind you could do this as simple as that.

BindingContext = new ViewModels.MainPages.LiveStreamViewModel(); closeButton.SetBinding(Button.CommandProperty, "BackCommand");

Upvotes: 0

Related Questions