Xamarin.Forms.Googlemaps showing blank - c#

I have installed Xamarin.Forms.Googlemaps 2.3.0.But I can see blank control in Android with text "Xamarin.Forms.GoogleMaps" and in iOS, nothing.
Where am i going wrong ?
In Androidmanifest, added:-
<meta-data android:name="com.google.android.geo.API_KEY" android:value="API_KEY"/>
In xaml,namespace is:-
xmlns:gmap="clr-namespace:Xamarin.Forms.GoogleMaps;assembly=Xamarin.Forms.GoogleMaps"
Control is:-
<gmap:Map x:Name="map"
Grid.Row="1"
HasZoomEnabled="True"
HeightRequest="{x:Static local:AppConstants.ActivityLogGfxContainerSize}"
InitialCameraUpdate="-23.68, -46.87, 13, 30, 60"
IsShowingUser="True"
MapLongClicked="map_MapLongClicked"
VerticalOptions="FillAndExpand"
WidthRequest="{x:Static local:AppConstants.PadThird}" />
in xaml.cs:-
protected override void OnBindingContextChanged()
{
base.OnBindingContextChanged();
this.locationViewModel = viewModel as LocationControlViewModel;
Check.IsNotNull(locationViewModel);
map.MyLocationEnabled = true;
map.MoveToRegion(Xamarin.Forms.GoogleMaps.MapSpan.FromCenterAndRadius(new Xamarin.Forms.GoogleMaps.Position(this.locationViewModel.Latitude, this.locationViewModel.Longitude), Xamarin.Forms.GoogleMaps.Distance.FromMiles(1)));
}
private async void map_MapLongClicked(object sender, Xamarin.Forms.GoogleMaps.MapLongClickedEventArgs e)
{
this.locationViewModel.Latitude = e.Point.Latitude;
this.locationViewModel.Longitude = e.Point.Longitude;
Xamarin.Forms.GoogleMaps.Pin pin = new Xamarin.Forms.GoogleMaps.Pin
{
Type = Xamarin.Forms.GoogleMaps.PinType.Place,
Position = new Xamarin.Forms.GoogleMaps.Position(this.locationViewModel.Latitude, this.locationViewModel.Longitude),
Label = "test"
};
map.Pins.Clear();
map.Pins.Add(pin);
map.MoveToRegion(Xamarin.Forms.GoogleMaps.MapSpan.FromCenterAndRadius(new Xamarin.Forms.GoogleMaps.Position(this.locationViewModel.Latitude, this.locationViewModel.Longitude), Xamarin.Forms.GoogleMaps.Distance.FromMiles(1)));
var stream = await map.TakeSnapshot();
}

Related

why when use listView some controls in page disappeared?

I use SearchBar to search from listView and I have other controls
but when page load just SearchBar appear and other controls disappear
like this image
and when search then select from listView the disappeared controls appears
like this image
my xaml code :
<StackLayout>
<SearchBar x:Name="search_trade"
TextChanged="search_trade_TextChanged"
/>
<ListView x:Name="list" ItemSelected="list_ItemSelected" >
<ListView.ItemTemplate>
<DataTemplate>
<TextCell Text="{Binding Name}" ></TextCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
<Editor x:Name="edit_trade"
FontSize="14"/>
</StackLayout>
my c# code :
private void search_trade_TextChanged(object sender, TextChangedEventArgs e)
{
if (search_trade.Text.Trim()==string.Empty)
{
list.IsVisible = false;
}
list.IsVisible = true;
if (string.IsNullOrEmpty(e.NewTextValue))
{
list.ItemsSource = tempdata;
}
else
{
list.ItemsSource = tempdata.Where(x => x.Name.ToLower().StartsWith(e.NewTextValue));
}
}
private void list_ItemSelected(object sender, SelectedItemChangedEventArgs e)
{
var item = (Contacts)e.SelectedItem;
edit_trade.Text = item.Name.ToString();
search_trade.Text = "";
list.IsVisible = false;
edit_trade.IsReadOnly = true;
}
code c# that I initially set the ItemsSource :
public Anti_biotic()
{
InitializeComponent();
active();
years_months();
frame_view.IsVisible = false;
trade();
}
private void trade()
{
tempdata = new List<Contacts>
{
new Contacts() { Name = "Amoclawin228.5mg/5mlsusp60ml"},
new Contacts() { Name = "Amoclawin 457mg / 5ml susp 60 ml"},
new Contacts() { Name = "Amoflux 250 mg susp 100 ml"},
};
}
how can I solve this issue?
you are not assigning the ListView's ItemsSource when the page loads. If the ListView doesn't have any data then it won't display anything
public Anti_biotic()
{
InitializeComponent();
active();
years_months();
frame_view.IsVisible = false;
// this method creates tempdata but doesn't do anything with it
trade();
// add this
list.ItemsSource = tempdata;
}

Create a hyperlink using Xamarin.Forms (xaml and c#)

I basically want to create a hyperlink in Xamarin.Forms using the label class. Basically, I want to following link to take the user to google.com in a web browser:
<Label Text="http://www.google.com/" />
I can't find anything in the Xamarin Forms API about this and the internet has vague and limited information on this topic in Xamarin.Forms.
Is this possible? If so, could someone please point me in the right direction? Thanks in advance to anyone who answers.
You can't really do this because Labels by default don't respond to user input, but you can achieve something similar with gestures
using Xamarin.Forms;
using Xamarin.Essentials;
Label label = new Label();
label.Text = "http://www.google.com/";
var tapGestureRecognizer = new TapGestureRecognizer();
tapGestureRecognizer.Tapped += async (s, e) => {
// Depreciated - Device.OpenUri( new Uri((Label)s).Text);
await Launcher.OpenAsync(new Uri(((Label)s).Text));
};
label.GestureRecognizers.Add(tapGestureRecognizer);
I made this little class to handle it:
public class SimpleLinkLabel : Label
{
public SimpleLinkLabel(Uri uri, string labelText = null)
{
Text = labelText ?? uri.ToString();
TextColor = Color.Blue;
GestureRecognizers.Add(new TapGestureRecognizer { Command = new Command(() => Device.OpenUri(uri)) });
}
}
And a bit more involved if you want to underline it too:
public class LinkLabel : StackLayout
{
private SimpleLinkLabel label;
public LinkLabel(Uri uri, string labelText = null, bool underlined = true)
{
// Remove bottom padding
Padding = new Thickness(Padding.Left, Padding.Top, Padding.Right, 0);
VerticalOptions = LayoutOptions.Center;
Children.Add(label = new SimpleLinkLabel(uri, labelText));
if (underlined)
Children.Add(new BoxView { BackgroundColor = Color.Blue, HeightRequest = 1, Margin = new Thickness(0, -8, 0, 0) });
}
public TextAlignment HorizontalTextAlignment { get { return label.HorizontalTextAlignment; } set { label.HorizontalTextAlignment = value; } }
}
The latter class inspired by this post: how to underline in xamarin forms
Edit: XLabs have a HyperLinkLabel too.
<Label LineBreakMode="WordWrap">
<Label.FormattedText>
<FormattedString>
<Span Text="Google">
<Span.GestureRecognizers>
<TapGestureRecognizer Tapped="Handle_Tapped" />
</Span.GestureRecognizers>
</Span>
</FormattedString>
</Label.FormattedText>
</Label>
public async void Handle_Tapped(object sender, EventArgs e)
{
await Browser.OpenAsync(new Uri(url), BrowserLaunchMode.SystemPreferred);
}
use a button and a xamarin.forms.theme nuget
<Button StyleClass = "Link"/>
https://developer.xamarin.com/guides/xamarin-forms/user-interface/themes/light/
If you want to do this with MVVM, you can create a Label with a blue text colour and a GestureRecognizers to hook it up to a Command:
<Label TextColor="Blue" Text="{Binding Model.LinkDescription}">
<Label.GestureRecognizers>
<TapGestureRecognizer Command="{Binding ClickCommand}" CommandParameter="{Binding Model.LinkURL}"/>
</Label.GestureRecognizers>
</Label>
In your ViewModel you can launch the default Browser using the Xamarin Essentials Nuget Package:
private Boolean IsValidUri(String uri)
{
try
{
new Uri(uri);
return true;
}
catch
{
return false;
}
}
public ICommand ClickCommand => new Command<string>(async (url) =>
{
try
{
if (!string.IsNullOrEmpty(url))
{
if (!url.Trim().StartsWith("http", StringComparison.OrdinalIgnoreCase))
{
url = "http://" + url;
}
if (IsValidUri(url))
{
await Browser.OpenAsync(new Uri(url), BrowserLaunchMode.SystemPreferred);
}
}
}
catch(Exception ex)
{
Debug.WriteLine(ex.Message);
}
});

Capture entry value in click event

I have a entry control added using c# to my xamarin.forms app. I also have a toolbaritem, on click of which I would like to save the data which is being entered by user.
I cannot access the text value in click event, I get this error:
Error 20 The name 'txtTest' does not exist in the current context
Here is my code sample:
public SettingsPage()
{
ToolbarItem Settings = new ToolbarItem();
Settings.Name = "Settings";
Settings.Clicked += OnClick_Settings;
Settings.Order = ToolbarItemOrder.Primaru;
ToolbarItems.Add(Settings);
loadData();
}
async public void loadData()
{
Label lblTest = new Label { Text = "Test", FontAttributes = FontAttributes.Bold };
Entry txtTest = new Entry();
StackLayout stLTest = new StackLayout
{
Padding = new Thickness(10, 0, 0, 0),
Children ={
lblTest,
txtTest
}
};
Content = stTest
}
async private void OnClick_Settings(object sender, EventArgs e)
{
var test= txtTest.Text;
}
In my OnClick_Settings, I cannot find text value.
you have txtTest in loadData() method.
you should move it out of there.
Do this
Entry txtTest;
async public void loadData()
{
Label lblTest = new Label { Text = "Test", FontAttributes = FontAttributes.Bold };
txtTest = new Entry();
StackLayout stLTest = new StackLayout
{
Padding = new Thickness(10, 0, 0, 0),
Children ={
lblTest,
txtTest
}
};
Content = stTest
}

Change image of a button that is on an element of a LongListSelector

I have this longListSelector:
<phone:LongListSelector
x:Name="ListaMensajesTablon"
ItemsSource="{Binding Mensajes}"
ItemTemplate="{StaticResource MensajesTablonDataTemplate}"
SelectionChanged="MensajeTablonSelected"/>
With this ItemTemplate:
<DataTemplate x:Key="MensajesTablonDataTemplate">
<Grid>
<Button MaxHeight="85" MaxWidth="95" MinHeight="85" MinWidth="95" Grid.Column="1" HorizontalAlignment="Right" VerticalAlignment="Center" Click="Button_Click" BorderBrush="Transparent">
<Button.Content>
<Image x:Name="imagenFav" MaxHeight="75" MaxWidth="75" MinHeight="75" MinWidth="75"
Source="{Binding userFav, Converter={StaticResource BoolToHeart}}" VerticalAlignment="Center" HorizontalAlignment="Center"/>
</Button.Content>
</Button>
</Grid>
</DataTemplate>
This code-behind:
private void Button_Click(object sender, RoutedEventArgs e)
{
botonFavPulsado = true;
botonAmor = (Button)sender;
}
private void MensajeTablonSelected(object sender, SelectionChangedEventArgs e)
{
if(botonFavPulsado)
{
var myItem = ((LongListSelector)sender).SelectedItem as MensajeTablon;
if(botonAmor!=null)
{
if (myItem.userFav)
{
botonAmor.Content = new Image
{
Source = new BitmapImage(new Uri("icons/heart.red.png", UriKind.Relative))
};
}
else
{
botonAmor.Content = new Image
{
Source = new BitmapImage(new Uri("icons/heart.white.png", UriKind.Relative))
};
}
}
botonFavPulsado = false;
}
}
I want to do is that when you press a button that is inside an element of LongListSelector change the picture . The first time I press the button enters in the function Button_Click and then enters in the function MensajeTablonSelected function and change the image (good). The problem is the second time I press the same button is entering in the function Button_Click function and does not enter in the function MensajeTablonSelected
Resume : ToggleButton in LongItemSelector working the first time but not the second one
Problem solved:
private void MensajeTablonSelected(object sender, SelectionChangedEventArgs e)
{
if (((LongListSelector)sender).SelectedItem != null)
if(botonFavPulsado)
{
var myItem = ((LongListSelector)sender).SelectedItem as MensajeTablon;
if(botonAmor!=null)
{
if (myItem.userFav)
{
botonAmor.Content = new Image
{
Source = new BitmapImage(new Uri("icons/heart.red.png", UriKind.Relative))
};
}
else
{
botonAmor.Content = new Image
{
Source = new BitmapImage(new Uri("icons/heart.white.png", UriKind.Relative))
};
}
}
botonFavPulsado = false;
//Unselect ITEM
((LongListSelector)sender).SelectedItem = null;
}
}
This solution have a problem, the function MensajeTablonSelected is called again.

Windows Phone Refresh button not working

I have a Windows phone application which gets a list of photos URLs from a SQL database depending what it uploaded.
The issue i have is users can add their own photos to that list but it does not refresh the list on the page so i added a refresh to re run the code but it still does not run.
Well the code runs but does not update the list box.
//get/clean these strings
int parkID = 0;
string parkName = string.Empty;
public photos()
{
InitializeComponent();
BuildLocalizedApplicationBar();
}
private void ThemeParkPhotos_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
if (e.Error == null)
{
try
{
//No errors have been passed now need to take this file and parse it
//Its in XML format
XDocument xdox = XDocument.Parse(e.Result);
//need a list for them to be put in to
List<Photos> themeparkPhoto = new List<Photos>();
themeparkPhoto.Clear();
XNamespace ns = "http://schemas.datacontract.org/2004/07/WCFServiceWebRole1";
//Now need to get every element and add it to the list
foreach (XElement item in xdox.Descendants(ns + "Photos"))
{
Photos content = new Photos();
content.ID = Convert.ToInt32(item.Element(ns + "ID").Value);
content.PhotoURL = Convert.ToString(item.Element(ns + "PhotoURL").Value);
//content.ID = Convert.ToInt32(item.Element(ns + "id").Value);
//content.ThemeParkName = item.Element(ns + "name").Value.ToString();
themeparkPhoto.Add(content);
}
ThemeParkPhoto.ItemsSource = null;
ThemeParkPhoto.ItemsSource = themeparkPhoto.ToList();
//Delete all the stuff
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
else
{
//There an Error
}
}
protected override void OnNavigatedTo(NavigationEventArgs e)
{
//This is to get the data that was passed from the home screen to which song to use!
base.OnNavigatedTo(e);
if ((NavigationContext.QueryString["pID"] == string.Empty) || (NavigationContext.QueryString["pName"] == string.Empty))
{
//if not show message box.
MessageBox.Show("Empty Vaules have been sent, Please got back and try again");
}
else
{
parkID = Convert.ToInt32(NavigationContext.QueryString["pID"]);
parkName = NavigationContext.QueryString["pName"].ToString();
PageName.Text = parkName;
GetThemeParkPhotos();
}
}
public void GetThemeParkPhotos()
{
WebClient ThemeParkPhotos = new WebClient();
ThemeParkPhotos.DownloadStringCompleted += ThemeParkPhotos_DownloadStringCompleted;
ThemeParkPhotos.DownloadStringAsync(new Uri("HIDDEDURL/viewphotos?format=xml&themeparkid=" + parkID));
//MessageBox.Show("Test if this works"+parkID);
}
private void BuildLocalizedApplicationBar()
{
ApplicationBar = new ApplicationBar();
ApplicationBar.Mode = ApplicationBarMode.Default;
ApplicationBar.Opacity = 1.0;
ApplicationBar.IsVisible = true;
ApplicationBar.IsMenuEnabled = true;
ApplicationBarIconButton AddButton = new ApplicationBarIconButton();
AddButton.IconUri = new Uri("/Images/add.png", UriKind.Relative);
AddButton.Text = "Add Photo";
ApplicationBar.Buttons.Add(AddButton);
AddButton.Click +=AddButton_Click;
//Dont add refresh button as it does not work at this time :(
ApplicationBarIconButton RefreshButton = new ApplicationBarIconButton();
RefreshButton.IconUri = new Uri("/Images/refresh.png", UriKind.Relative);
RefreshButton.Text = "Refresh";
ApplicationBar.Buttons.Add(RefreshButton);
RefreshButton.Click += RefreshButton_Click;
}
private void RefreshButton_Click(object sender, EventArgs e)
{
GetThemeParkPhotos();
}
private void AddButton_Click(object sender, EventArgs e)
{
//need to send them to add a photo page with details.
NavigationService.Navigate(new Uri("/TakePhoto.xaml?pID=" + parkID + "&pName=" + parkName, UriKind.Relative));
}
Here the Code for the ListBox
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
<ListBox Height="559" HorizontalAlignment="Left" Margin="6,20,0,0" x:Name="ThemeParkPhoto" VerticalAlignment="Top" Width="444" FontSize="30" ItemsSource="{Binding}">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Vertical">
<TextBlock x:Name="ID" Text="{Binding ID}"></TextBlock>
<Image x:Name="PhotoURL" Source="{Binding PhotoURL}" />
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Grid>
I have removed the URL to save the API, That code does run and fill it but why does it not refresh the List Box correctly?
Many Thanks
Thank to being sent here : C# WebClient disable cache
Turns out that Windows phone web client caches the file meaning it never download it again until the app is refreshed. By using a random number generator and adding it to the then of the URL it will always download the file allowing for a refresh.

Categories