How to set BindingContext of MasterDetailPage.Master - xamarin

I have a MasterDetailPage.Master and a Login page. After the login I call a WebService that returns a filled class to me, and its working, even the BindingContext is getting the values, but the fields on the Page are empty. How do I set the binding context of the MasterDetailPage.Master if it is rendering before the Login page?
This is for a profile page in the MasterDetailPage.Master, using a WebService to fill the binding. I already tried to call a new instance of the MasterDetailPage on the OnDesappearing of the Login page, but not success.
MainPage.xaml
<?xml version="1.0" encoding="utf-8" ?>
<MasterDetailPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:views="clr-namespace:HCTaNaMao.Views"
x:Class="HCTaNaMao.Views.MainPage">
<MasterDetailPage.Master>
<views:InformacoesUsuario />
</MasterDetailPage.Master>
<MasterDetailPage.Detail>
<NavigationPage>
<NavigationPage.Icon>
<OnPlatform x:TypeArguments="FileImageSource">
<On Platform="iOS" Value="tab_feed.png"/>
</OnPlatform>
</NavigationPage.Icon>
<x:Arguments>
<views:Menu />
</x:Arguments>
</NavigationPage>
</MasterDetailPage.Detail>
</MasterDetailPage>
MasterDetailPage.Master.xaml
<?xml version="1.0" encoding="utf-8" ?>
<TabbedPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="HCTaNaMao.Views.InformacoesUsuario"
Title="Dados do Usuário">
<TabbedPage.Children>
<ContentPage Title="Usuário">
<StackLayout Padding="0,50,0,0">
<Image BackgroundColor="LightGray" HorizontalOptions="Center" Source="HC_logo.png"></Image>
<Frame
OutlineColor="Silver"
VerticalOptions="CenterAndExpand"
HorizontalOptions="Fill"
Margin="15">
<StackLayout
HorizontalOptions="Center"
VerticalOptions="Center">
<Label x:Name="lblNome" Text="{Binding nome}" FontSize="18" HorizontalTextAlignment="Center"></Label>
<BoxView Color="Gray" HeightRequest="1" HorizontalOptions="Fill"/>
<Label x:Name="lblProntuario" Text="{Binding prontuario}" FontSize="18" HorizontalTextAlignment="Center"></Label>
<BoxView Color="Gray" HeightRequest="1" HorizontalOptions="Fill"/>
<Button x:Name="btnEditar" Text="Perfil" TextColor="White" WidthRequest="110"
HorizontalOptions="Center" BackgroundColor="SteelBlue" BorderRadius="20"/>
</StackLayout>
</Frame>
</StackLayout>
</ContentPage>
<ContentPage Title="Perfil">
<Frame
OutlineColor="Silver"
VerticalOptions="CenterAndExpand"
HorizontalOptions="Fill"
Margin="15">
<StackLayout>
<TableView>
<TableRoot>
<TableSection Title="Dados Pessoais">
<EntryCell x:Name="cellNome" Placeholder="Nome"
Text="{Binding nome}" IsEnabled="True"></EntryCell>
<EntryCell Placeholder="Data de Nascimento" x:Name="cellNasc"
Text="{Binding data_nascimento}" IsEnabled="True"></EntryCell>
<EntryCell Placeholder="CPF" Keyboard="Numeric" x:Name="cellCpf"
Text="{Binding cpf}" IsEnabled="True"></EntryCell>
<EntryCell Placeholder="CNS" Keyboard="Numeric" x:Name="cellCns"
Text="{Binding cns}" IsEnabled="True"></EntryCell>
</TableSection>
</TableRoot>
</TableView>
<Button Text="Editar"
IsVisible="False">
</Button>
<Button x:Name="btnSalvar"
Text="Salvar"
IsVisible="True" TextColor="White" WidthRequest="110"
HorizontalOptions="Center" BackgroundColor="SteelBlue" BorderRadius="20"></Button>
</StackLayout>
</Frame>
</ContentPage>
</TabbedPage.Children>
</TabbedPage>
MaterDetailPage.xaml.cs
namespace HCTaNaMao.Views
{
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class InformacoesUsuario : TabbedPage
{
HCTMWebService service = new HCTMWebService();
HCTMPacienteDTO paciente;
public InformacoesUsuario ()
{
InitializeComponent();
btnEditar.Command = new Command(() => this.CurrentPage = this.Children[1]);
btnSalvar.Command = new Command(() => this.CurrentPage = this.Children[0]);
paciente = service.InformacoesPaciente(Login.seq_cliente);
BindingContext = paciente;
}
}
}
I expect MasterPage fields are filled by the Binding

How do I set the binding context of the MasterDetailPage.Master if it is rendering before the Login page?
About binding context of MasterDetailedPage.Master, I do one sample, you can take a look:
MainPage:
<MasterDetailPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:local="clr-namespace:MasterDetailPageNavigation;assembly=MasterDetailPageNavigation"
x:Class="MasterDetailPageNavigation.MainPage">
<MasterDetailPage.Master>
<local:MasterPage x:Name="masterPage" />
</MasterDetailPage.Master>
<MasterDetailPage.Detail>
<NavigationPage>
<x:Arguments>
<local:ContactsPage />
</x:Arguments>
</NavigationPage>
</MasterDetailPage.Detail>
</MasterDetailPage>
public partial class MainPage : MasterDetailPage
{
public MainPage()
{
InitializeComponent();
masterPage.listView.ItemSelected += OnItemSelected;
if (Device.RuntimePlatform == Device.UWP)
{
MasterBehavior = MasterBehavior.Popover;
}
}
void OnItemSelected(object sender, SelectedItemChangedEventArgs e)
{
var item = e.SelectedItem as MasterPageItem;
if (item != null)
{
Detail = new NavigationPage((Page)Activator.CreateInstance(item.TargetType));
masterPage.listView.SelectedItem = null;
IsPresented = false;
}
}
}
MasterPage:
I don't understand why your masterPage is TabbedPage, I think it should be contentpage,that has Listview to display detailed page title.
<ContentPage
x:Class="MasterDetailPageNavigation.MasterPage"
xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:local="using:MasterDetailPageNavigation"
Title="Personal Organiser"
Padding="0,40,0,0"
IconImageSource="hamburger.png">
<StackLayout>
<ListView
x:Name="listView"
x:FieldModifier="public"
ItemsSource="{Binding items}">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<Grid Padding="5,10">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="30" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<Image Source="{Binding IconSource}" />
<Label Grid.Column="1" Text="{Binding Title}" />
</Grid>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</StackLayout>
public partial class MasterPage : ContentPage
{
public ObservableCollection<MasterPageItem> items { get; set; }
public MasterPage()
{
InitializeComponent();
//load data from service or other.
items = new ObservableCollection<MasterPageItem>()
{
new MasterPageItem(){ Title="Contacts", IconSource="contacts.png",TargetType=typeof(ContactsPage)},
new MasterPageItem(){Title="TodoList",IconSource="todo.png",TargetType=typeof(TodoListPage)},
new MasterPageItem(){Title="Reminders",IconSource="reminders.png",TargetType=typeof(ReminderPage)}
};
this.BindingContext = this;
}
}
About MasterDetailedPage, I suggest you can take a look:
https://learn.microsoft.com/en-us/xamarin/xamarin-forms/app-fundamentals/navigation/master-detail-page

Related

Xamarin App opens different Page from Navigation.PushAsync() Page

Description
Xamarin application opens different Page upon NavigationPage.Pushaync().
NavigationPage.Asyncpush() is called within a ButtonClicked Method.
That different page used to be the one being pushed but it no longer is.
ViewModel.cs
private async void OnAboutUsClicked()
{
var modifiedContactUs = new ModifiedContactUs() { BackgroundColor = ResourceColourModel.BackgroundColor };
await Application.Current.MainPage.Navigation.PushAsync(modifiedContactUs);
}
ModifiedContactUs.xaml
<?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="Project.Views.Pages.ModifiedContact"
xmlns:mapObject="clr-namespace:Xamarin.Forms.Maps;assembly=Xamarin.Forms.Maps">
<ContentPage.Content>
<StackLayout>
<Grid BackgroundColor="white">
<mapObject:Map x:Name="mapId" HasZoomEnabled="True" MapType="Street">
</mapObject:Map>
</Grid>
</StackLayout>
</ContentPage.Content>
</ContentPage>
ModifiedContactUs.xaml.cs
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
namespace Project.Views.Pages
{
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class ModifiedContactUs : ContentPage
{
public ModifiedContactUs()
{
InitializeComponent();
}
}
ContactUs.xaml(The different Page)
<?xml version="1.0" encoding="utf-8" ?>
<customControl:CustomContentPage
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"
xmlns:map ="clr-namespace:Xamarin.Forms.Maps;assembly=Xamarin.Forms.Maps"
xmlns:ffimageloading="clr-namespace:FFImageLoading.Svg.Forms;assembly=FFImageLoading.Svg.Forms"
xmlns:customControl="clr-namespace:Project.CustomControls.Renderers"
xmlns:templates_navbar="clr-namespace:Project.Views.Templates.Menus"
xmlns:fontAwesome="clr-namespace:Project._Utilities"
mc:Ignorable="d"
x:Class="Project.Views.Pages.ContactUs"
>
<ContentPage.Content>
<StackLayout BackgroundColor="Transparent" Spacing="0">
<templates_navbar:NavBar DotMenu_IsVisible="False" BackButton_IsVisible="True"/>
<Grid BackgroundColor="white">
<Grid.RowDefinitions>
<RowDefinition Height=".33*"/>
<RowDefinition Height=".07*"/>
<RowDefinition Height=".6*"/>
</Grid.RowDefinitions>
<Grid Grid.Row="0">
<Grid.ColumnDefinitions>
<ColumnDefinition Width=".7*"/>
<ColumnDefinition Width=".3*"/>
</Grid.ColumnDefinitions>
<StackLayout Grid.Column="0" Padding="10">
<StackLayout>
<Label
Text="Company Name"
FontAttributes="Bold"
FontSize="Medium"
FontFamily="Lato-Bold"
VerticalOptions="CenterAndExpand"
HorizontalOptions="StartAndExpand"
/>
<Label
Text="{Binding Address}"
FontFamily="Lato-Bold"
VerticalOptions="CenterAndExpand"
HorizontalOptions="StartAndExpand"
/>
</StackLayout>
<StackLayout>
<Label
Text="Opening Times"
FontAttributes="Bold"
FontSize="Medium"
FontFamily="Lato-Bold"
VerticalOptions="CenterAndExpand"
HorizontalOptions="StartAndExpand"
/>
<Label
x:Name="weekdays_lbl"
Text="{Binding Weekday}"
FontFamily="Lato-Bold"
VerticalOptions="CenterAndExpand"
HorizontalOptions="StartAndExpand"
/>
<Label
x:Name="weekend_lbl"
Text="{Binding Weekend}"
FontFamily="Lato-Bold"
VerticalOptions="CenterAndExpand"
HorizontalOptions="StartAndExpand"
/>
</StackLayout>
</StackLayout>
<StackLayout Grid.Column="1">
<StackLayout VerticalOptions="CenterAndExpand">
<Button
x:Name="CallUsBtn"
Text="Call Us"
TextColor="White"
BackgroundColor="{StaticResource PrimaryColour}"
FontFamily="Lato-Bold"
FontSize="12"
BorderWidth="2"
BorderColor="White"
Margin="1"
CornerRadius="22"
Command="{Binding PhoneCommand}"
/>
<Button
x:Name="MessageUsBtn"
Text="Message"
TextColor="White"
BackgroundColor="{StaticResource PrimaryColour}"
FontFamily="Lato-Bold"
FontSize="12"
BorderWidth="2"
BorderColor="White"
Margin="1"
CornerRadius="22"
Command="{Binding EmailCommand}"
/>
<Button
x:Name="RequestCallBack"
Text="Request CallBack"
TextColor="White"
BackgroundColor="{StaticResource AccentColour}"
FontFamily="Lato-Bold"
FontSize="11"
BorderWidth="2"
BorderColor="White"
Margin="1"
CornerRadius="22"
Command="{Binding CallbackCommand}"
/>
</StackLayout>
</StackLayout>
</Grid>
<Grid Grid.Row="1" Padding="5">
<Grid.ColumnDefinitions>
<ColumnDefinition Width=".25*"/>
<ColumnDefinition Width=".25*"/>
<ColumnDefinition Width=".25*"/>
<ColumnDefinition Width=".25*"/>
</Grid.ColumnDefinitions>
<StackLayout Grid.Column="0">
<Grid VerticalOptions="CenterAndExpand">
<Image
Source="{FontImage FontFamily={StaticResource MaterialFontFamily},
Glyph={x:Static fontAwesome:IconFonts.Facebook}, Color=#1877F2,Size=60}"
HeightRequest="80"
/>
<Button Clicked="SocialMediaBtnHandler" BackgroundColor="Transparent" Margin="5, 0" CommandParameter="facebook"/>
</Grid>
</StackLayout>
<StackLayout Grid.Column="1">
<Grid VerticalOptions="CenterAndExpand">
<Image
Source="{FontImage FontFamily={StaticResource MaterialFontFamily},
Glyph={x:Static fontAwesome:IconFonts.Twitter}, Color=#00ACED, Size=60}"/>
<Button Clicked="SocialMediaBtnHandler" BackgroundColor="Transparent" Margin="5, 0" CommandParameter="twitter"/>
</Grid>
</StackLayout>
<StackLayout Grid.Column="2">
<Grid VerticalOptions="CenterAndExpand">
<Image
Source="{FontImage FontFamily={StaticResource MaterialFontFamily},
Glyph={x:Static fontAwesome:IconFonts.Linkedin}, Color=#0E76A8, Size=60}"/>
<Button Clicked="SocialMediaBtnHandler" BackgroundColor="Transparent" Margin="5, 0" CommandParameter="linkedIn"/>
</Grid>
</StackLayout>
<StackLayout Grid.Column="3">
<Grid VerticalOptions="CenterAndExpand" Padding="2">
<ffimageloading:SvgCachedImage
Source="social_logo_instagram.png"
HeightRequest="40"/>
<Button Clicked="SocialMediaBtnHandler" BackgroundColor="Transparent" Margin="5, 0" CommandParameter="instagram"/>
</Grid>
</StackLayout>
</Grid>
<Grid Grid.Row="2">
<Grid>
<StackLayout Grid.Row="0" Padding="5">
<map:Map x:Name="mapObject" HasZoomEnabled="True" MapType="Street">
<map:Map.ItemTemplate>
<DataTemplate>
<map:Pin
Position="{Binding Position}"
Address="{Binding Address}"
Label="{Binding PlaceName}"
/>
</DataTemplate>
</map:Map.ItemTemplate>
</map:Map>
</StackLayout>
</Grid>
</Grid>
</Grid>
<AbsoluteLayout BackgroundColor="Red" HorizontalOptions="FillAndExpand" VerticalOptions="FillAndExpand" AbsoluteLayout.LayoutBounds="0, 0, 1, 1" AbsoluteLayout.LayoutFlags="SizeProportional">
</AbsoluteLayout>
</StackLayout>
</ContentPage.Content>
</customControl:CustomContentPage>
ContactUs.xaml.cs (The different page)
using Project._SharedData;
using Project.CustomControls.Renderers;
using Project.Models;
using Project.ViewModels;
using Rg.Plugins.Popup.Services;
using System;
using Xamarin.Essentials;
using Xamarin.Forms;
using Xamarin.Forms.Maps;
using Xamarin.Forms.Xaml;
namespace Project.Views.Pages
{
[XamlCompilation(XamlCompilationOptions.Compile)]
[System.ComponentModel.DesignTimeVisible(false)]
public partial class ContactUsPage : CustomContentPage
{
ContactUsVM _ContactUsVM;
public ContactUsPage()
{
InitializeComponent();
BindingContext = _ContactUsVM = new ContactUsVM();
initMap();
configureDisplay();
setFontOpeningTime();
}
protected override void OnAppearing()
{
base.OnAppearing();
_ContactUsVM.OnAppearing();
configureDisplay();
}
protected override void OnDisappearing()
{
base.OnDisappearing();
_ContactUsVM.OnDisappearing();
try
{
if (PopupNavigation.Instance != null)
PopupNavigation.Instance.PopAsync(true);
}
catch (Exception) { }
}
private void setFontOpeningTime()
{
DayOfWeek day = DateTime.Now.DayOfWeek;
// Set the font based on whether current day is weekday or weekend
if ((day == DayOfWeek.Saturday) || (day == DayOfWeek.Sunday))
{
weekend_lbl.FontAttributes = FontAttributes.Bold;
}
else
{
weekdays_lbl.FontAttributes = FontAttributes.Bold;
}
}
private void configureDisplay()
{
if (!string.IsNullOrEmpty(SharedPrefs.UserSessionEmail))
{
RequestCallBack.IsVisible = true;
MessageUsBtn.Text = "Email";
}
else
{
RequestCallBack.IsVisible = false;
MessageUsBtn.Text = "Message";
}
}
private async void SocialMediaBtnHandler(object sender, EventArgs e)
{
string socialMediaName = (sender as Button).CommandParameter.ToString().ToLower();
await Launcher.OpenAsync(SocialMediaModel.WebLink(socialMediaName));
}
private void initMap()
{
try
{
double latitude = Convert.ToDouble(SharedData.CompanyDetailsList[0].Latitude);
double longitude = Convert.ToDouble(SharedData.CompanyDetailsList[0].Longitude);
mapObject.MoveToRegion(MapSpan.FromCenterAndRadius(new Position(latitude, longitude), Distance.FromMeters(100)));
mapObject.ItemsSource = SharedData.CompanyDetailsList;
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
}
}
Expected behavior
To navigate to a new Page named ModifiedContactUs
Actual behavior:
Navigates to page called named ContactUs
Basic Information:
Android Build:
-minimum level 21
-Target level 30
Devices:
-Huawei Y6 2019
-API level 29
-Pixel 5
-API level 30
Notes
This question is different to from the first question I asked recently (Where the device crashes). This is behavior happens on all devices I test on except the one from that first question
Expected behavior
To navigate to a new Page named ModifiedContactPage
Actual behavior:
Navigates to page called named ContactUsPage
From your code I saw you just push to ModifiedContactUs not ModifiedContactPage .
var modifiedContactUs = new ModifiedContactUs() { BackgroundColor = ResourceColourModel.BackgroundColor };
await Application.Current.MainPage.Navigation.PushAsync(modifiedContactUs);
Suggestion
Try to add breakpoint to see if it triggers button click event es expected .
Delete the old class and try again .
Delete the app from the device and try again .
This worked: Clone the repo into a new folder as a new project and copy the files and changes to this new repo.
Attempted configuration solutions that did not work: Restarting visual studio. Untick and Tick Debug Mode. Untick and tick Deploy in Configuration Manager under Build. In Android Properties> android Options making sure debugging is checked and debugger is Xamarin.

Xamarin.Forms GestureRecognizers not working on Command

Code in the xaml page:
<StackLayout VerticalOptions="FillAndExpand" HorizontalOptions="FillAndExpand">
<CollectionView ItemsSource="{Binding MeniElementi}">
<CollectionView.ItemsLayout>
<GridItemsLayout Orientation="Vertical"
Span="2" />
</CollectionView.ItemsLayout>
<CollectionView.ItemTemplate>
<DataTemplate>
<Frame Padding="10" WidthRequest="140" HeightRequest="140">
<Frame BackgroundColor="AliceBlue" WidthRequest="120" HeightRequest="120" HasShadow="True" CornerRadius="10" Padding="10" VerticalOptions="FillAndExpand" HorizontalOptions="FillAndExpand" >
<StackLayout>
<Image Source="http://www.clker.com/cliparts/l/u/5/P/D/A/arrow-50x50-md.png" WidthRequest="70" HeightRequest="70" >
<Image.GestureRecognizers>
<TapGestureRecognizer
Command="{Binding LoadElements}"
/>
</Image.GestureRecognizers>
</Image>
<Label Text="{Binding Title}" HeightRequest="50" WidthRequest="100" HorizontalTextAlignment="Center" VerticalTextAlignment="Center" />
</StackLayout>
</Frame>
</Frame>
</DataTemplate>
</CollectionView.ItemTemplate>
</CollectionView>
</StackLayout>
Code in xaml.cs:
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class Menu: ContentPage
{
MenuViewModel viewModel = new MenuViewModel();
public Menu()
{
InitializeComponent();
BindingContext = viewModel;
}
}
Code in viewmodel.cs
public class MenuViewModel :BaseViewModel, INotifyPropertyChanged
{
public Command LoadElements { get; set; }
public ObservableCollection<Meni> MeniElementi { get; set; }
public MenuViewModel()
{
LoadElements= new Command(execute: async () => await ExecuteElements());
MeniElementi = new ObservableCollection<Meni>() {
new Meni(){Title="Transatcions" ,Picture="xxx"},
new Meni(){Title="Transatcions" ,Picture="xxx"},
};
}
async Task ExecuteElements()
{
try
{
await Application.Current.MainPage.Navigation.PushAsync(new InfoPage());
}
catch (Exception ex)
{
Debug.WriteLine(ex);
}
finally
{
}
}
LoadElements Command not fired. Loading starting menu , showing menu elements just command not working to navigate to another page. Using Xamarin.Forms.Command. On other pages working normal with Command
You could reset the binding path of the tap . So that you can handle the logic in the same command .
in the ContentPage (which contains the CollectionView)
<?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:Name="Page" //set the name of page
x:Class="xxx.xxxPage">
<TapGestureRecognizer Command="{Binding Source={x:Reference Page},Path=BindingContext.LoadElements}"
you need to call the command on the ViewModel of the Page for that you need to do this:-
<Image.GestureRecognizers>
<TapGestureRecognizer Command="{Binding LoadElements, Source={x:Reference Name=ThisPage}}" />
</Image.GestureRecognizers>
And put x:Name="ThisPage" in the ContentPage tag of the xaml at the top of the page.
Let me know if you face difficulties.

Binding Xamarin XAML to code behind properties (ListView)

I want to bind my code-behind property, which is a list, to a XAML ListView. However, my ListView is never populated and I have no idea why.
<?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="BLEPl.EvaluationPage"
Title="Evaluation">
<ContentPage.Content>
<StackLayout Padding="0,20,0,20">
<ListView HasUnevenRows="True" IsVisible="True" x:Name="TableLayout" ItemsSource="{Binding Path=SensorValues}">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<Grid>
<Label Style="{StaticResource TitleLabel}" Grid.Column="0" Grid.Row="0" Text="Zeitstempel: " />
<Label Style="{StaticResource DataLabel}" Grid.Column="1" Grid.Row="0" Text="{Binding TimeStamp}" />
<Label Style="{StaticResource TitleLabel}" Grid.Column="0" Grid.Row="1" Text="Wert: " />
<Label Style="{StaticResource DataLabel}" Grid.Column="1" Grid.Row="1" Text="{Binding Value}" />
<Label Style="{StaticResource TitleLabel}" Grid.Column="0" Grid.Row="2" Text="Sensor: " />
<Label Style="{StaticResource DataLabel}" Grid.Column="1" Grid.Row="2" Text="{Binding Sensor.Name}" />
</Grid>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</StackLayout>
</ContentPage.Content>
</ContentPage>
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class EvaluationPage : ContentPage
{
private ObservableCollection<SensorValue> SensorValues = new ObservableCollection<SensorValue>();
public EvaluationPage ()
{
InitializeComponent ();
using (var context = new BlepContext(true))
{
var repo = new BLEPRepository(context);
SensorValues = new ObservableCollection<SensorValue>(repo.GetAllSensorValues());
}
}
}
When I run this, my ListView doesn't contain any items. I do not get errors and my app compiles fine. Am I doing something wrong here?
<ListView HasUnevenRows="True" IsVisible="True" x:Name="TableLayout" ItemsSource="{Binding SensorValues}">
you can only bind to public properties, and you need to set a BindingContext for the page
// needs to be a PUBLIC PROPERTY
public ObservableCollection<SensorValue> SensorValues { get; set; }
public EvaluationPage ()
{
InitializeComponent ();
// set the BindingContext
this.BindingContext = this;
using (var context = new BlepContext(true))
{
var repo = new BLEPRepository(context);
SensorValues = new ObservableCollection<SensorValue>(repo.GetAllSensorValues());
}
}

Prism and Control Templates

I'm trying to rewrite the sample "SimpleThemeWithTemplateBinding" that uses ControlTemplates, with Prism.
I also added a simple
HeaderText = "changed";
in the button to change the HeaderText in the ControlTemplate, and it works, in the original sample.
So I copied the template in my app.xaml:
<ControlTemplate x:Key="TealTemplate">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="0.1*" />
<RowDefinition Height="0.8*" />
<RowDefinition Height="0.1*" />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="0.05*" />
<ColumnDefinition Width="0.95*" />
</Grid.ColumnDefinitions>
<BoxView Grid.ColumnSpan="2" Color="Teal" />
<Label Grid.Column="1" Text="{TemplateBinding BindingContext.HeaderText}" TextColor="White" VerticalOptions="Center" />
<ContentPresenter Grid.Row="1" Grid.ColumnSpan="2" />
<BoxView Grid.Row="2" Grid.ColumnSpan="2" Color="Teal" />
<Label Grid.Row="2" Grid.Column="1" Text="(c) Xamarin 2016" TextColor="White" VerticalOptions="Center" />
</Grid>
</ControlTemplate>
and just changed
{TemplateBinding HeaderText}
to
{TemplateBinding BindingContext.HeaderText}
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:prism="clr-namespace:Prism.Mvvm;assembly=Prism.Forms"
prism:ViewModelLocator.AutowireViewModel="True"
x:Class="TestAppNSPrism7.Views.PrismContentPage9">
<ContentPage.Content>
<ContentView x:Name="contentView" Padding="0,0,0,0" ControlTemplate="{StaticResource TealTemplate}" >
<StackLayout>
<Label Text="Welcome to Xamarin.Forms! page1"
VerticalOptions="CenterAndExpand"
HorizontalOptions="CenterAndExpand" />
<Label Text="Buazz"
VerticalOptions="CenterAndExpand"
HorizontalOptions="CenterAndExpand" />
<Button Command="{Binding ButtonChangeValueCommand}" Text="Change value" ></Button>
</StackLayout>
</ContentView>
</ContentPage.Content>
</ContentPage>
VIEWMODEL:
public class PrismContentPage9ViewModel : ViewModelBase
{
ControlTemplate tealTemplate;
private string _headerText = "test";
public string HeaderText
{
get
{
return _headerText;
}
set { SetProperty(ref _headerText, value); }
}
public PrismContentPage9ViewModel(INavigationService navigationService) : base(navigationService)
{
tealTemplate = (ControlTemplate)Application.Current.Resources["TealTemplate"];
}
private DelegateCommand _buttonChangeValueCommand;
public DelegateCommand ButtonChangeValueCommand =>
_buttonChangeValueCommand ?? (_buttonChangeValueCommand = new DelegateCommand(ExecuteButtonChangeValueCommand));
void ExecuteButtonChangeValueCommand()
{
HeaderText = "changed";
}
}
The Page gets loaded correctly, with the ControlTemplate, and the HeaderText is "test".
So it seems the HeaderText binding with the ControlTemplate is working.
But when I set the HeaderText to "changed", the Label doesn't get updated.
I debugged and checked that once I press the button it goes through ExecuteButtonChangeValueCommand() and SetProperty(ref _headerText, value)
Any suggestion?
Thanks!
I changed the TemplateBinding from :
Text="{TemplateBinding BindingContext.HeaderText}"
to:
Text="{TemplateBinding Parent.BindingContext.HeaderText}"
and it updates now when I press your changed button.
I believe its due to the template not having a binding context automatically set but the template's parent (PrismContentPage9) has its BindingContext auto-wired from Prism's AutowireViewModel property, e.g.,
prism:ViewModelLocator.AutowireViewModel="True"
Let me know if that works for you.

error in my Navigation. PushAsync (new DetailsPage (monkey))

I'm following the following example of carousel with the listview, more when I go to open Navigation.PushAsync the item in the listview is called only the first item, on all items clicked his name only the first item, a position error?
void Handle_ItemSelected(object sender, SelectedItemChangedEventArgs e)
{
var monkey = ((ListView)sender).SelectedItem as Monkey;
if (monkey == null)
return;
Navigation.PushAsync(new DetailsPage(monkey));
}
https://blog.xamarin.com/flip-through-items-with-xamarin-forms-carouselview/
EDIT
MonkeysPage.xaml
<?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="Monkeys.Views.MonkeysPage"
xmlns:design="clr-namespace:Monkeys;assembly=Monkeys"
xmlns:controls="clr-namespace:ImageCircle.Forms.Plugin.Abstractions;assembly=ImageCircle.Forms.Plugin.Abstractions"
xmlns:cv="clr-namespace:Xamarin.Forms;assembly=Xamarin.Forms.CarouselView"
BindingContext="{x:Static design:ViewModelLocator.MonkeysViewModel}"
x:Name="MonkeysPage"
Title="Traditional Monkeys">
<ContentPage.Content>
<ListView ItemsSource="{Binding MonkeysGrouped}"
ItemSelected="Handle_ItemSelected"
HasUnevenRows="true"
GroupShortNameBinding = "{Binding Key}"
IsGroupingEnabled = "true"
GroupDisplayBinding = "{Binding Key}">
<ListView.Header>
<cv:CarouselView x:Name="CarouselZoos" ItemsSource="{Binding Path=BindingContext.Zoos, Source={x:Reference MonkeysPage}}" HeightRequest="200">
<cv:CarouselView.ItemTemplate>
<DataTemplate>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="*"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<Image Grid.RowSpan="2" Aspect="AspectFill" Source="{Binding ImageUrl}"/>
<StackLayout Grid.Row="1" BackgroundColor="#80000000" Padding="12">
<Label TextColor="White" Text="{Binding Name}" FontSize="16" HorizontalOptions="Center" VerticalOptions="CenterAndExpand"/>
</StackLayout>
</Grid>
</DataTemplate>
</cv:CarouselView.ItemTemplate>
</cv:CarouselView>
</ListView.Header>
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<Grid Padding="10" RowSpacing="10" ColumnSpacing="10">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<controls:CircleImage
BorderColor="Aqua"
BorderThickness="3"
HeightRequest="66"
HorizontalOptions="CenterAndExpand"
VerticalOptions="CenterAndExpand"
Aspect="AspectFill"
WidthRequest="66"
Grid.RowSpan="2"
Source="{Binding Image}"/>
<Label Grid.Column="1"
Text="{Binding Name}"
VerticalOptions="End"/>
<Label Grid.Column="1"
Grid.Row="1"
VerticalOptions="Start"
Text="{Binding Location}"/>
</Grid>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
MonkeysPage.xaml.cs
public MonkeysPage()
{
InitializeComponent();
BindingContext = new MonkeysViewModel();
}
async void Handle_ItemSelected(object sender, SelectedItemChangedEventArgs e)
{
var monkey = e.SelectedItem as Monkey;
if (monkey == null)
return;
await Navigation.PushAsync(new DetailsPage(monkey)); // always await Navigations
((ListView)sender).SelectedItem = null;
}
DetailsPage.xaml
<?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="Monkeys.Views.DetailsPage"
xmlns:design="clr-namespace:Monkeys;assembly=Monkeys"
xmlns:controls="clr-namespace:ImageCircle.Forms.Plugin.Abstractions;assembly=ImageCircle.Forms.Plugin.Abstractions"
BindingContext="{x:Static design:ViewModelLocator.DetailsViewModel}"
Title="{Binding Monkey.Name}">
<ContentPage.Content>
<ScrollView>
<StackLayout Padding="10">
<controls:CircleImage
BorderColor="Aqua"
BorderThickness="3"
HeightRequest="200"
WidthRequest="200"
HorizontalOptions="CenterAndExpand"
Aspect="AspectFill"
Source="{Binding Monkey.Image}"/>
<Label Text="{Binding Monkey.Name}" FontAttributes="Bold"/>
<Label Text="{Binding Monkey.Location}" FontSize="Micro"/>
<Label Text="{Binding Monkey.Details}" FontSize="Large"/>
</StackLayout>
</ScrollView>
</ContentPage.Content>
DetailsPage
public partial class DetailsPage : ContentPage
{
public DetailsPage(Monkey monkey)
{
InitializeComponent();
}
}
You're doing everything good except that you forgot to reset the SelectedItem to null, that's why you are getting always the first list item clicked.
Your code should look like this:
async void Handle_ItemSelected(object sender, SelectedItemChangedEventArgs e)
{
var monkey = e.SelectedItem as Monkey;
if (monkey == null)
return;
await Navigation.PushAsync(new DetailsPage(monkey)); // always await Navigations
((ListView)sender).SelectedItem = null;
}
P.S. Make your method async so you don't cause UI Thread to block
EDIT
Try to get the selected item from SelectedItemChangedEventArgs.
var monkey = e.SelectedItem as Monkey;
UPDATE
Okay the SelectedItem is being updated successfully but the 'Monkey Item' on the ViewModel behind the DetailsPage is not!
So on DetailsPage add this line:
public partial class DetailsPage : ContentPage
{
public DetailsPage(Monkey monkey)
{
InitializeComponent();
BindingContext = new DetailsViewModel(monkey); // Update the BindingContext
}
}
And remove this line on the DetailsPage.xaml:
BindingContext="{x:Static design:ViewModelLocator.DetailsViewModel}"

Resources