Xamarin ControlTemplate set BindingContext - xaml

I've got a contentcontrol to reuse some layout code.
Now I want to display the contentcontrol twice on one page, but with different content. How can I set the Binding Context of the ContentControl, so that it displays firstItem.Title in the first ContentView, and secondItem.Title in the second ContentView?
Shortened Code, just to view what i mean:
<ControlTemplate x:Name="ContainerControl">
<StackLayout>
<Label Text="{Binding Title}" />
</StackLayout>
</ControlTemplate>
<!-- Display the first item -->
<ContentView Item="{Binding firstItem}" ControlTemplate="{StaticResource ContainerControl" />
<!-- Display the second item -->
<ContentView Item="{Binding secondItem}" ControlTemplate="{StaticResource ContainerControl" />
Item Class / ViewModel Properties:
public class Item
{
public string Title { get; set; }
}
public Item firstItem
{
get;
set;
}
public Item secondItem
{
get;
set;
}

Related

Why doesnt my image bind until I save my contentpage unless I save and reload

I'm currently trying to bind a few properties when I click a button and it pushes a new page.
Starting from the top, this is how my app is setup
public App()
{
InitializeComponent();
MainPage = new NavigationPage(new MainPage());
}
I have a "MainPage" which is essentially the first page that shows when starting the app.
In my MainPage.xaml
I've set the BindingContext to the MainViewModel
<ContentPage.BindingContext>
<viewModels:MainViewModel/>
</ContentPage.BindingContext>
And I also have a button which has it's Command bound to a Command in my MainViewModel
<Button Text="New Goal"
HeightRequest="50" WidthRequest="100"
TextColor="White"
Margin="10"
CornerRadius="4"
Command="{Binding NewGoalCommand}">
<Button.Background>
<LinearGradientBrush StartPoint="0,0" EndPoint="0,1">
<GradientStop Color="#8FDF70" Offset="0.1" />
<GradientStop Color="#1DBE95" Offset="1.0" />
</LinearGradientBrush>
</Button.Background>
</Button>
The MainViewModel is pretty straightforward. It has a Command property which I initialize in the constructor
public ObservableCollection<Item> Items { get; set; } = new ObservableCollection<Item>();
public Command NewGoalCommand { get; set; }
public MainViewModel()
{
NewGoalCommand = new Command(() => ShowNewGoalPage());
}
private async void ShowNewGoalPage()
{
await Application.Current.MainPage.Navigation.PushAsync(new NewGoal(SelectedItem));
}
NewGoal.xaml
As you can see in the code it's invoking NewGoal which is my second page which shows up when I click the button, this page does show up when I click the button which to me, indicates that the binding was successful.
The same goes for this page, I'm setting the BindingContext to my other ViewModel which is responsible for it's corresponding view, like so
<ContentPage.BindingContext>
<viewModel:NewGoalViewModel/>
</ContentPage.BindingContext>
And I've also added components which are going to bind to it's corresponding property so that when I click "Save" it adds that item to the collection inside the MainViewModel
<ContentPage.Content>
<StackLayout Spacing="0">
<Image WidthRequest="50" HeightRequest="50"
Margin="10"
Source="{Binding ItemModel.ImageSource}"/>
<StackLayout Margin="20,0,20,0"
Spacing="0">
<Label Text="Title"/>
<Entry />
</StackLayout>
<StackLayout Margin="20,20,20,0"
Spacing="0">
<Label Text="Description"/>
<Entry />
</StackLayout>
<StackLayout Margin="20,20,20,0"
Spacing="0">
<Label Text="Type"/>
<Picker ItemsSource="{Binding ItemModel.Type}" />
</StackLayout>
<StackLayout Margin="20,20,20,0"
Spacing="0">
<Label Text="Price"/>
<Entry Keyboard="Numeric"/>
</StackLayout>
<Button Command="{Binding SaveCommand}"
Text="Save"
VerticalOptions="End">
</Button>
</StackLayout>
</ContentPage.Content>
And here is the NewGoalViewModel
class NewGoalViewModel : MainViewModel
{
public Item ItemModel { get; set; }
public Command SaveCommand { get; set; }
public NewGoalViewModel()
{
ItemModel = new Item();
ItemModel.Title = "Title";
ItemModel.Description = "Description";
ItemModel.Type = SavingsType.Other;
ItemModel.Price = 19.00f;
ItemModel.ImageSource = "cash.jpg";
SaveCommand = new Command(() => AddGoal());
}
private void AddGoal()
{
Items.Add(new Item { Title = "Rainy Day", Type = SavingsType.Other, Price = 100.00, ImageSource = "cash.jpg" });
}
}
The issue
So when I start the app and I click the first button, it takes me to the next page.
when I land on that page, it should show me an Image at the top. It's bound to a property which I've assigned in the constructor ItemModel.ImageSource = "cash.jpg";
The issue is however is that it doesnt actually bind, resulting in the image not showing until I save the NewGoal.xaml page and it reloads. Once it's done reloading it shows the image.
Try modifying
private Item itemModel { get; set; }
public Item ItemModel
{
get { return itemModel ; }
set
{
itemModel = value;
OnPropertyChanged();
}
}
and inherit your ViewModel to : INotifyPropertyChanged
and add this to implement
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged([CallerMemberName] string propertyName = "")
{
var changed = PropertyChanged;
if (changed == null)
return;
changed.Invoke(this, new PropertyChangedEventArgs(propertyName));
}

Xamarin Forms, Dynamic ScrollView in XAML

I'm wanting to create a GUI that has a similar to what the following code generates, a scroll of frames.
However I want to be able to have a scroll of dynamic content frames, ideally in XAML and populated with an Item source. I don't think this is possible without creating a custom view based on itemsview from what I can see. ListView and CollectionView don't quite do what I want.
I think I need to use the preview CarouselView, I was wondering if there is a way of doing what I'm after without.
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="FlexTest.MainPage">
<ContentPage.Resources>
<Style TargetType="Frame">
<Setter Property="WidthRequest" Value="300"/>
<Setter Property="HeightRequest" Value="500"/>
<Setter Property="Margin" Value="10"/>
<Setter Property="CornerRadius" Value="20"/>
</Style>
</ContentPage.Resources>
<ScrollView Orientation="Both">
<FlexLayout>
<Frame BackgroundColor="Yellow">
<FlexLayout Direction="Column">
<Label Text="Panel 1"/>
<Label Text="A Panel"/>
<Button Text="Click Me"/>
</FlexLayout>
</Frame>
<Frame BackgroundColor="OrangeRed">
<FlexLayout Direction="Column">
<Label Text="Panel 2"/>
<Label Text="Another Panel"/>
<Button Text="Click Me"/>
</FlexLayout>
</Frame>
<Frame BackgroundColor="ForestGreen">
<FlexLayout Direction="Column">
<Label Text="Panel 3"/>
<Label Text="A Third Panel"/>
<Button Text="Click Me"/>
</FlexLayout>
</Frame>
</FlexLayout>
</ScrollView>
</ContentPage>
Thanks
Andy.
Do you want to implement a scrollable view and each child contains multiple content that can be scrolled horizontally?
For this feature, try to display the CarouselView in a ListView.
Check the code:
<ListView ...>
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<CarouselView>
<CarouselView.ItemTemplate>
<DataTemplate>
...
</DataTemplate>
</CarouselView.ItemTemplate>
</CarouselView>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
Tutorial about CarouselView:
https://learn.microsoft.com/en-us/xamarin/xamarin-forms/user-interface/carouselview/introduction
Preface: I hope I understood your request correctly :)
If by dynamic content you mean having a dynamic ItemTemplate then you can try doing following:
Step One:
Define an ItemTemplateSelector, you can give it w.e name you want. In this class we will define what sort of templates we have, let us say we have the three which you defined: Yellow, OrangeRed, ForestGreen
public class FrameTemplateSelector : DataTemplateSelector {
public DataTemplate YellowFrameTemplate {get; set;}
public DataTemplate OrangeRedFrameTemplate {get; set;}
public DataTemplate ForestGreenFrameTemplate {get; set;}
public FrameTemplateSelector() {
this.YellowFrameTemplate = new DataTemplate(typeof (YellowFrame));
this.OrangeRedFrameTemplate = new DataTemplate(typeof (OrangeRedFrame));
this.ForestGreenFrameTemplate = new DataTemplate(typeof (ForestGreenFrame));
}
//This part is important, this is how we know which template to select.
protected override DataTemplate OnSelectTemplate(object item, BindableObject container) {
var model = item as YourViewModel;
switch(model.FrameColor) {
case FrameColorEnum .Yellow:
return YellowFrameTemplate;
case FrameColorEnum .OrangeRed:
return OrangeRedFrameTemplate;
case FrameColorEnum .ForestGreen:
return ForestGreenFrameTemplate;
default:
//or w.e other template you want.
return YellowFrameTemplate;
}
}
Step Two:
Now that we have defined our Template Selector let us go ahead and define our templates, in this case our Yellow, OrangeRed, and ForestGreen frames respectively. I will simply show how to make one of them since the others will follow the same paradigm excluding, with of course the color changing. Let's do the YellowFrame
In the XAML you will have:
YellowFrame.xaml:
<StackLayout xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:d="http://xamarin.com/schemas/2014/forms/design"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
x:Class="YourNameSpaceGoesHere.YellowFrame">
<Frame BackgroundColor="Yellow">
<FlexLayout Direction="Column">
<Label Text="Panel 1"/>
<Label Text="A Panel"/>
<Button Text="Click Me"/>
</FlexLayout>
</Frame>
</StackLayout>
In the code behind:
YellowFrame.xaml.cs:
public partial class YellowFrame : StackLayout {
public YellowFrame() {
InitializeComponent();
}
}
Step Three
Now we need to create our ViewModel that we will use for our ItemSource that we will apply to FlexLayout, per the documentation for Bindable Layouts, any layout that "dervies from Layout" has the ability to have a Bindable Layout, FlexLayout is one of them.
So let us make the ViewModel, I will also create an Enum for the Color frame we want to render as I showed in the switch statement in step one, however, you can choose what ever means of deciding how to tell which template to load; this is just one possible example.
BaseViewModel.cs:
public abstract class BaseViewModel : INotifyPropertyChanged {
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = ""){
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
public virtual void CleanUp(){
}
}
ParentViewModel.cs:
public class ParentViewModel: BaseViewModel {
private ObservableCollection<YourViewModel> myViewModels {get; set;}
public ObservableCollection<YourViewModel> MyViewModels {
get { return myViewModels;}
set {
myViewModels = value;
OnPropertyChanged("MyViewModels");
}
}
public ParentViewModel() {
LoadData();
}
private void LoadData() {
//Let us populate our data here.
myViewModels = new ObservableCollection<YourViewModel>();
myViewModels.Add(new YourViewModel {FrameColor = FrameColorEnum .Yellow});
myViewModels.Add(new YourViewModel {FrameColor = FrameColorEnum .OrangeRed});
myViewModels.Add(new YourViewModel {FrameColor = FrameColorEnum .ForestGreen});
MyViewModels = myViewModels;
}
}
YourViewModel.cs:
public class YourViewModel : BaseViewModel {
public FrameColorEnum FrameColor {get; set;}
}
FrameColorEnum.cs:
public enum FrameColorEnum {
Yellow,
OrangeRed,
ForestGreen
}
We're almost there, so what we have done so far is we defined our view models that we will use on that page, the final step is to update our overall XAML where we will call our Template Selector. I will only update the snippets needed.
<ContentPage
...
**xmlns:views="your namespace where it was defined here,
normally you can just type the name of the Selector then have VS add the proper
namespace and everything"**
<ContentPage.Resources>
<!--New stuff below-->
<ResourceDictionary>
<views:FrameTemplateSelector x:Key="FrameTemplateSelector"/>
</ResourceDictionary>
</ContentPage.Resources>
<ScrollView Orientation="Both">
<FlexLayout BindableLayout.ItemsSource="{Binding MyViewModels, Mode=TwoWay}"
BindableLayout.ItemTemplateSelector ="{StaticResource FrameTemplateSelector}"/>
</ScrollView>
Live Picture:

Two way binding with ObservableCollection<string> in Xamarin Forms

I am using a bindable StackLayout to show a series of Entry bound to an ObservableCollection<string> (Addresses in the the viewModel down).
It is not a problem to show on the UI the content of the collection, but if I modify the content of any of the Entry, it does not get reflected back in the original ObservableCollection
Here is the view model:
public class MainViewModel
{
public ObservableCollection<string> Addresses { get; set; }
public ICommand AddCommand { get; private set; }
public MainViewModel()
{
AddCommand = new Command(AddEmail);
Addresses = new ObservableCollection<string>();
Addresses.Add("test1");
Addresses.Add("test2");
}
void Add()
{
AddCommand(string.Empty);
}
}
And here is the view:
<?xml version="1.0" encoding="utf-8"?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:d="http://xamarin.com/schemas/2014/forms/design"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
x:Class="TestList.MainPage"
x:Name="page">
<StackLayout>
<StackLayout Orientation="Horizontal">
<Label Text="Addresses"
FontSize="Large"
HorizontalOptions="FillAndExpand"
VerticalOptions="Center"/>
<Button Command="{Binding AddCommand}"
Text="+" FontSize="Title"
VerticalOptions="Center"/>
</StackLayout>
<StackLayout BindableLayout.ItemsSource="{Binding Addresses}">
<BindableLayout.ItemTemplate>
<DataTemplate>
<StackLayout Orientation="Horizontal">
<Entry Text="{Binding ., Mode=TwoWay}" HorizontalOptions="FillAndExpand"/>
<Button Text="-" FontSize="Title""/>
</StackLayout>
</DataTemplate>
</BindableLayout.ItemTemplate>
</StackLayout>
</StackLayout>
</ContentPage>
I suspect that this is due to the fact that I am working on strings, and as such they cannot be modified in place. Do you have a suggestion on how to solve this problem without introducing a wrapper class or similar?
If you want to change the value of source in code behind by editing the text in Entry .You need to implement the interface INotifyPropertyChanged in class of ObservableCollection .
Define a model class
public class MyModel: INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
string content;
public string Content
{
get
{
return content;
}
set
{
if (content != value)
{
content = value;
OnPropertyChanged("Content");
}
}
}
}
in ViewModel
public ObservableCollection<MyModel> Addresses { get; set; }
Addresses = new ObservableCollection<MyModel>();
Addresses.Add(new MyModel() {Content = "test1" });
Addresses.Add(new MyModel() { Content = "test2" });
in xaml
<Entry Text="{Binding Content, Mode=TwoWay}" HorizontalOptions="FillAndExpand"/>
You really need a wrapper class for this to work, besides if the syntax is too lengthy you can install PropertyCHanged.Fody package
Then all you need to do is add this tag:
[AddINotifyPropertyChangedInterface]
public class MainViewModel
{
public List<Address> Addresses { get; set; }
And in the wrapper class:
[AddINotifyPropertyChangedInterface]
public class Address
{
public string Street { get; set; }

UWP ListView DataTemplate Bind to Item instead of Property

How do you bind an item in a data template to the item itself, instead of a property of that item?
I have a user control that takes an item as a model. Given these models:
public class Car
{
public string Name { get; set; }
public Color color { get; set; }
public string Model { get; set; }
}
public MyUserControl : UserControl
{
public Car Model { get; set; }
}
public MyPage : Page
{
public ObservableCollection<Car> CareList { get; set; }
}
I want to do something like this in XAML:
<ListView ItemsSource="{x:Bind CarList}">
<ListView.ItemTemplate>
<DataTemplate x:DataType="models:Car">
<StackPanel>
<!-- Binding to properties of Car is simple... -->
<TextBlock Text="{x:Bind Name}">
<!-- But what if I want to bind to the car itself ??? -->
<userControls:MyUserControl Model="{x:Bind Car}">
</userControls:MyUserControl>
</StackPanel>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
The comment from #user2819245 is correct, if you do not specify the Path of the binding then the DataContext object will be bound directly instead.
In UWP, if your list source can change at runtime or is delay loaded, then you may also need to specify the Mode=OneWay, this is due to {x:Bind} defaulting to a OneTime binding mode.
This example includes how to set the Mode property in both use cases
<ListView ItemsSource="{x:Bind CarList, Mode=OneWay}">
<ListView.ItemTemplate>
<DataTemplate x:DataType="models:Car">
<StackPanel>
<!-- Binding to properties of Car is simple... -->
<TextBlock Text="{x:Bind Name, Mode=OneWay}">
<!-- Binding to the car itself (as the DataContext of this template) -->
<userControls:MyUserControl Model="{x:Bind Mode=OneWay}">
</userControls:MyUserControl>
</StackPanel>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>

Mock data not showing when bound to ICollectionView

If I bound my ListBox to ViewModels ObservableCollection or XAML resourced CollectionViewSource, the mock data shows while in design.
Sometimes CollectionViewSource stops showing this data because of some XAML changes, but after rebuilding the code it fills controls back with fake data again.
Grouping, sorting and filtering in my case are controlled in ViewModel (and retried from database) so I decided to move over to ICollectionView property based in ViewModel. Unfortunately Views are no longer getting mock data at all.
Here is simple example of my approaches:
<Window x:Class="Test.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:Test"
mc:Ignorable="d"
d:DataContext="{d:DesignInstance local:MainWindowViewModel }"
Title="MainWindow" Height="100" Width="525"
>
<Window.Resources>
<CollectionViewSource x:Key="ItemsCollectionViewSource" Source="{Binding ItemsObservableCollection}"/>
</Window.Resources>
<UniformGrid Columns="6">
<ListBox ItemsSource="{Binding ItemsObservableCollection}" Background="WhiteSmoke" />
<ListBox ItemsSource="{Binding Source={StaticResource ItemsCollectionViewSource}}" Background="LightYellow" />
<ListBox ItemsSource="{Binding ItemsICollectionView}" Background="WhiteSmoke" />
<ListBox ItemsSource="{Binding ItemsCollectionView}" Background="LightYellow" />
<ListBox ItemsSource="{Binding ItemsListCollectionView}" Background="WhiteSmoke" />
<ListBox ItemsSource="{Binding ItemsBackCollectionViewSource}" Background="LightYellow" />
</UniformGrid>
</Window>
code behind:
namespace Test
{
public partial class MainWindow
{
public MainWindow()
{
DataContext = new MainWindowViewModel();
InitializeComponent();
}
}
}
and ViewModel:
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Windows.Data;
namespace Test
{
public class MainWindowViewModel
{
public ICollectionView ItemsICollectionView { get; set; }
public CollectionView ItemsCollectionView { get; set; }
public ListCollectionView ItemsListCollectionView { get; set; }
public ObservableCollection<string> ItemsObservableCollection { get; set; }
public CollectionViewSource ItemsBackCollectionViewSource { get; set; }
public MainWindowViewModel()
{
ItemsObservableCollection = new ObservableCollection<string> {"a", "b", "c"};
ItemsICollectionView = CollectionViewSource.GetDefaultView(ItemsObservableCollection);
ItemsCollectionView = CollectionViewSource.GetDefaultView(ItemsObservableCollection) as CollectionView;
ItemsListCollectionView = CollectionViewSource.GetDefaultView(ItemsObservableCollection) as ListCollectionView;
ItemsBackCollectionViewSource = new CollectionViewSource {Source = ItemsObservableCollection};
}
}
}
None of methods I have tried in order to move CollectionViewSource to ViewModel allows me to see mock data:
I did some debug comparison on those controls, but they are set pretty same in a run time. I'm not aware of ability to debug at design time.
Is there something I'm missing, or it has to be that way?
Thanks