Skip to content

Instantly share code, notes, and snippets.

@chrisriesgo
Created July 12, 2015 15:37
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chrisriesgo/2e9c88fa346e57745e73 to your computer and use it in GitHub Desktop.
Save chrisriesgo/2e9c88fa346e57745e73 to your computer and use it in GitHub Desktop.
An example showing how to have dynamic item templates driven off of the bound viewmodels.
public class App : Application
{
public IEnumerable<ICarouselViewModel> _pages;
public App()
{
_pages = new List<ICarouselViewModel>()
{
new PageOneViewModel(),
new PageTwoViewModel()
};
// The root page of your application
MainPage = new ContentPage {
Content = new ListView() {
ItemsSource = _pages,
ItemTemplate = new DataTemplate(typeof(DynamicTemplateLayout))
}
};
}
}
public class DynamicTemplateLayout : ViewCell
{
protected override void OnBindingContextChanged()
{
base.OnBindingContextChanged();
var vm = BindingContext as ICarouselViewModel;
var page = vm.View;
page.BindingContext = vm;
View = page;
}
}
public interface ICarouselViewModel
{
ContentView View { get; }
}
public class PageOneViewModel : ICarouselViewModel
{
public ContentView View
{
get { return new PageOne(); }
}
public Color PageOneColor
{
get { return Color.Red; }
}
}
public class PageTwoViewModel : ICarouselViewModel
{
public ContentView View
{
get { return new PageTwo(); }
}
public string PageTwoTitle
{
get { return "Page Two"; }
}
}
public class PageOne : ContentView
{
public PageOne()
{
var box = new BoxView() {
WidthRequest = 100,
HeightRequest = 100,
};
box.SetBinding<PageOneViewModel>(BoxView.ColorProperty, vm => vm.PageOneColor);
Content = box;
}
}
public class PageTwo : ContentView
{
public PageTwo()
{
var label = new Label() {
Font = Font.SystemFontOfSize(20),
};
label.SetBinding<PageTwoViewModel>(Label.TextProperty, vm => vm.PageTwoTitle);
Content = label;
}
}
@biliktamas79
Copy link

This implementation puts and shows the dynamic viewmodels into a ListView, but the title suggests that it is a CarouselView using dynamic viewModels as items.
I need a CarouselView implementation that can show items with multiple dynamic viewModel types like your implementation here with a ListView.
I tried to mix this code with your CarouselView here: https://github.com/chrisriesgo/xamarin-forms-carouselview
but sadly I did not succeed.
I've spend a lot of time, tried in a lot of ways, but I always get some runtime framework exceptions. I suppose it's something about the bindings, but the exceptions are not so helpful.

How should I modify this or the CarouselView sample app code to have items with multiple viewModels and Views?

Thanks,

Tamás

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment