How to accomplish a whatsapp like popup dialog selector in Xamarin Forms ?
because i want the user to choose between Camera and Gallery when he click add photo.
How to accomplish a whatsapp like popup dialog selector ?
Change and control device orientation programmatically in Xamarin.forms
Hi,
Is there any cross-platform way to change/control device/UI orientation programmatically in Xamarin.forms ?
Suppose i an writing a cross-platform app using Xamarin.forms where i have 2 pages. After launching the app, first page(Camera View) will appear only in landscape mood. On that page i have a button. If i press that button then another page will appear modally only at portrait mood. Is it possible to achieve ? If yes then how can i do that ?
Any sample code on changing and controlling device orientation programmatically in Xamarin.forms will be very helpful.
Thanks in advance.
Detecting Device Orientation
How detect the orientation of the device (Portrait or Landscape) in Xamarin Forms?
Binding property changed not firing Xamarin.Forms + Prism
Hello everyone!
I'm trying to consume a REST API and update the Text property of some Entry views. But as soon as I get a JSON response and set some properties of my POCO class the view it's not updating.
Take a look in my code:
ViewModel:
namespace MyApp.ViewModels
{
public class CompanyInfoPageViewModel : ViewModelBase //which inherits BindableBase
{
private APIClient _apiClient;
public CompanyInfoPageViewModel(
INavigationService navigationService,
IPageDialogService pageDialogService,
APIClient apiClient) : base(navigationService, pageDialogService)
{
_apiClient = apiClient;
Company = new Company();
}
private Company company;
public Company Company
{
get { return company; }
set { SetProperty(ref company, value); }
}
//Fired on TextChanged of txtCEP Entry
public async void FindCEP(string text)
{
var response = await _apiClient.GetAsync("cep/" + text);
if (response.IsSuccessStatusCode)
{
var json = await response.ToJObjectAsync();
var error = json.Value<string>("errors");
if (error == null)
{
var data = json["data"];
Company.Endereco = json["data"]["log_no_abrev"].ToString();
Company.Bairro = json["data"]["bairro"].ToString();
Company.Cidade = json["data"]["cidade"].ToString();
//And the view it's not updated ;(
}
else
{
await PageDialogService.DisplayAlertAsync("Ops", error, "OK");
}
}
else
{
//displays another message
}
}
}
public class Company
{
public string Endereco { get; set; }
public string Bairro { get; set; }
public string Cidade { get; set; }
public string CEP { get; set; }
}
}
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"
xmlns:prism="clr-namespace:Prism.Mvvm;assembly=Prism.Forms"
prism:ViewModelLocator.AutowireViewModel="True"
x:Class="MyApp.Views.CompanyInfo"
Title="Dados da empresa">
<StackLayout HorizontalOptions="FillAndExpand" VerticalOptions="Center">
<StackLayout HorizontalOptions="FillAndExpand" VerticalOptions="Center" Padding="0,20,0,0">
<Label Text="Endereço" FontSize="Large"/>
<Entry Text="{Binding Company.CEP}" Placeholder="CEP" x:Name="txtCEP" />
<Entry Text="{Binding Company.Endereco, Mode=TwoWay }" Placeholder="Rua, Av..." HorizontalOptions="FillAndExpand"/>
<Entry Text="{Binding Company.Bairro}" Placeholder="Bairro" />
<Entry Text="{Binding Company.Cidade}" Placeholder="Cidade" HorizontalOptions="FillAndExpand"/>
</StackLayout>
<Button Command="{Binding SalvarCommand}" Text="Salvar" Style="{StaticResource buttonPrimary}"/>
</StackLayout>
</ContentPage>
Am I doing something wrong?
Binding TextColor of label to a property in the viewmodel
I have a label and I want to dynamically bind the textcolor property of this label to a property in my viewmodel. I have two doubts - does the property in my viewmodel has to be of type string or Color? And how do I do this thing?
All the previously answered questions haven't worked for me even when I have tried using an IValueConverter.
Thanks!
Minimum and Maximum date in Date picker
How set values for minimum and maximum date in datepicker in xamarin forms??
using Plugin.Fingerprint.CrossFingerprint.Current.AuthenticateAsync
I.m using Plugin.Fingerprint.CrossFingerprint.Current.AuthenticateAsync to validate the fingerprint, like
var authenticationResult = await Plugin.Fingerprint.CrossFingerprint.Current.AuthenticateAsync("touch", _cancel.Token);
if i give registerd fingerprint then im getting success result but if i give non registered fingerprint it is not giving result as failed,m it is just showing the fingerprint in red color, so i want to get the fail status to show a message.
TextureView with Custom Renderer
Hi!
I would like to have a camera stream in a view that I can add in XAML or code on my PLC project.
Xamarin forms sample renderer solves this, but they're using a SurfaceView and not a TextureView with the Android renderer, which disables the opportunity to save a bitmap from the stream.
Anyone that have implemented something similar?
Would love to have the same functionality with iOS as well.
Xamarin Forms sample
https://developer.xamarin.com/guides/xamarin-forms/application-fundamentals/custom-renderer/view/
Native Android Sample, using TextureView but used as a Activity:
https://developer.xamarin.com/recipes/android/other_ux/textureview/display_a_stream_from_the_camera/
/Oliver
Bindable Property is not working.
Hello All,
I have created bindable property as below;
public static readonly BindableProperty ColorProperty = BindableProperty.Create(
"ClockColor",
typeof(string),
typeof(AnalogClock), "#007a94");
public string ClockColor
{
get
{
return (string)GetValue(ColorProperty);
}
set
{
SetValue(ColorProperty, value);
}
}
And I am assigning value to 'ClockColor' as;
<ucontrol:AnalogClock WidthRequest="150" HeightRequest="150" ClockColor="#000"/>
But this is not working.
Can anyone know, What is wrong in this code.
ListView item stays selected if it's tapped more than once
Hi everyone,
I'm currently having some issues with the ListView control. I had a requirements in my app which necessitated a bit of extra work to implement using Xamarin Forms' listview:
Selection can change from a background task, without any user input.
Selection needs to be confirmed by the user via a dialog box.
Basically my app is a list of emergency states, if the current state is changed from somewhere else (desktop app or another mobile device), the listview selection must change. It's also possible to have no active emergency states (let's call it 'None'), which means no selected item in the listview. My listview itemssource is set via databinding but I use the OnSelected event because I need to confirm, and cancel if necessary, the selection.
It works except for one scenario. Initial context is no emergency state (no item is selected in the listview).
(1) Click on a list item (and confirm the dialog box)
(2) Item is correctly selected (OnSelected event is fired, selected item background color is changed)
(3) Tap on the selected item once again (the UI doesn't change and the OnSelected event is not fired, as expected)
(4) From another device, set the state back to 'None' (no selected item)
(5) My app sets the ListView.SelectedItem to null. Everything else seems to be coherent in the view model.
Problem: The item still has the selected background color. The ListView SelectedItem is null, my ViewModel datasource is as expected. This case works fine if you skip step #3. I tried with a simple text cell to make sure that it wasn't my custom cell renderer.
The only way to get out of this is to click another item in the listview, then the previously selected item will go back to the normal background color.
Any idea on how to prevent this issue?
UWP: WebView sometimes doesn't appear
I've been seeing a really tricky, intermittent issue in our XF app on UWP when running on the simulator, Surface, and Surface Books. This is only an issue on UWP. It never fails when running the app on iOS. It happens on Debug or Release mode, and even the version installed from the Windows App Store.
We use a lot of ContentViews in the app and one of them contains a WebView that we're using to display some very basic html text. Depending on where this ContentView is used in the app, and between different devices/simulator, it usually fails to show about 15-30% of the time.
I've attempted to isolate the issue in a repro project unsuccessfully. My current theory is that it might be related to the number of layouts in the view hierarchy. Using the Visual Tree, I can confirm that the panel with the WebView is there, it just doesn't show. In testing, I'm using a bright pink background to show when it renders.
Any ideas? Has anyone seen something like this?
I'll attach some screenshots: what it should look like, what it looks like when it fails, and the visual tree.
[Custom Renderer/XF] Getting Native Camera Stream To Work
Please, before I explain and give code snippets, note that I do not want/need what Xamarin Forms Labs offers. That camera is intent, which is impractical to me, and I want to be able to customize the camera.
Anyway, I am attempting to get a native camera stream to work inside of Xamarin Forms. So far, I have a ContentPage called CameraPage:
And a custom renderer called CameraFrameRenderer:
The big question is, in the code above, how do I correctly pass in the CameraPreview (Code below, taken from example in monodroid) and allow viewing inside of Xamarin Forms.
Here is the code for the CameraPreview. Essentially, I want to be able to set the contents of ContentPage to that view. I have no idea how to do this part, and have researched/tried for hours now.
How to create bottom menu in xamarin.forms using xaml?
I want to create bottombar(menu) in xamarin.forms xaml page.
Is there any control of xaml?
Couple of problems with ListView context actions (UWP)
I'm having a problem with the list view context action (delete) on a UWP project. I have no idea of the same issues apply on iOS or Android.
1) If you add three items to a list, use the context action to delete one of them, then add another new item to the list, then you cannot delete the third item on the list any longer even tho the context menu appears. The context action command parameter references the previously deleted item even tho it no longer exists in the datasource. You can delete any of the other items, but then you get a similar unable to delete issue with any other new ones that you add.
2) If the list view's viewcell is a stack layout of horizontal labels, swiping on whitespace between labels does not display the context menu. Using a Grid behaves as expected.
<?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="Views.TestPage2">
<StackLayout>
<Button Text="Button" Command="{Binding ButtonCommand}" />
<Label Text="{Binding Counter}"/>
<ListView x:Name="ItemsListView" ItemsSource="{Binding DataSource}"
HorizontalOptions = "LayoutOptions.FillAndExpand"
VerticalOptions = "LayoutOptions.FillAndExpand">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<ViewCell.ContextActions>
<MenuItem Clicked="OnDelete" CommandParameter="{Binding .}" Text="Delete" IsDestructive="True" />
</ViewCell.ContextActions>
<StackLayout Orientation="Horizontal" Padding="10,0,10,0">
<Label Text="{Binding Title}" FontSize="Medium" HorizontalOptions="StartAndExpand"/>
<Label Text="{Binding Quantity}" FontSize="Medium" HorizontalOptions="EndAndExpand"/>
</StackLayout>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</StackLayout>
</ContentPage>
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;
namespace Views
{
public partial class TestPage2 : ContentPage
{
public TestPage2()
{
InitializeComponent();
var model = new TestListViewModel();
this.BindingContext = model;
}
public void OnDelete(object sender, EventArgs e)
{
var mi = ((MenuItem)sender);
((TestListViewModel)this.BindingContext).RemoveItem((TestListViewDataItem)mi.CommandParameter);
}
}
public class TestListViewModel : INotifyPropertyChanged
{
public TestListViewModel()
{
DataSource = new ObservableCollection<Views.TestListViewDataItem>();
ButtonCommand = new Command(() =>
{
Counter++;
DataSource.Add(new Views.TestListViewDataItem(string.Format("item : {0}", Counter), 0));
});
}
public void RemoveItem(TestListViewDataItem item)
{
DataSource.Remove(item);
}
public Command ButtonCommand { get; set; }
public ObservableCollection<TestListViewDataItem> DataSource { get; set; }
public TestListViewDataItem SelectedItem { get; set; }
public int Counter { get; set; }
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged(string PropertyName)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
handler(this, new PropertyChangedEventArgs(PropertyName));
}
}
public class TestListViewDataItem
{
public TestListViewDataItem(string title, int quantity)
{
Title = title;
Quantity = quantity;
}
public string Title { get; set; }
public int Quantity { get; set; }
}
}
How to fire entry_completed with numeric keyboard without return key.
Hi,
I'm building an app with an entry with numeric keyboard. Because an numeric keyboard has not a return key, How do I get the value entered in this entry?
I have now an event handler entry_completed. But I get not the value entered in the entry.
My code:
void EntryCompletedAmount(object sender, EventArgs e)
{
string amountTxt = ((Entry)sender).Text;
amount = Convert.ToDecimal(amountTxt);
}
It would be nice when the user has entered some value and clicked outside the keyboard the value will be stored. Is this possible?
Kind regards,
Tom Buyvoets
Forms9Patch: Simplify multi-device image management in your PCL Xamarin.Forms mobile apps
Announcement of Form9Patch
Xamarin Forms is great for developing apps on Android and iOS but it is missing two important tools for developers: scalable images and PCL multi-screen image management. Android developers use NinePatch bitmaps and the drawable directory naming convention for this purpose. Likewise, iOS developers use ResizeableImageWithCapInsets and the @2x, @3x, @4x file naming convention for this purpose.
Forms 9 Patch enhances Xamarin Forms to enable multi-resolution / multi-screen image management to PCL apps for iOS and Android.
What is it?
Simply stated, Forms9Patch is two separate elements (Image and ImageSource) which are multi-screen / multi-resolution extensions of their Xamarin Forms counterparts.
Forms9Patch.ImageSource
Xamarin Forms provides native iOS and Android multi-screen image management (described here). This requires storing your iOS images using the native iOS schema and storing your Android images using the Android schema. In other words, duplicative efforts to get the same results on both Android and iOS. Forms9Patch.ImageSource extends Xamarin.Forms.ImageSource capabilities to bring multi-screen image management to your PCL assemblies - so you only have to generate and configure your app's image resources once. Forms9Patch.ImageSource is a cross-platform implementation to sourcing multi-screen images in Xamarin Forms PCL apps as embedded resources.
Forms9Patch.Image
Forms9Patch.Image compliments Xamarin.Forms.Image to provide Xamarin Forms with a scaleable image element. Scalable images are images that fill their parent view by stretching in designated regions. The source image for the Forms9Patch.Image element can be specified either as a Forms9Patch.ImageSource or a Xamarin.Forms.ImageSource. Supported file formats are NinePatch (.9.png), .png, .jpg, .jpeg, .gif, .bmp, and .bmpf.
Example code
After adding the file bubble.9.png to your PCL project assembly as an EmbeddedResource, you can display it using something like the following:
var bubbleImage = new Forms9Patch.Image () {
Source = ImageSource.FromResource("MyDemoApp.Resources.bubble.9.png"),
HeightRequest = 110,
}
var label = new label () {
Text = "Forms9Path NinePatch Image",
HorizontalOptions = LayoutOptions.Center,
}
Example XAML
In Xamarin Forms, access to embedded resources from XAML requires some additional work. Unfortunately, Forms9Patch is no different. As with Xamarin Forms, you will need (in the same assembly as your embedded resource images) a simple custom XAML markup extension to load images using their ResourceID.
[ContentProperty ("Source")]
public class ImageMultiResourceExtension : IMarkupExtension
{
public string Source { get; set; }
public object ProvideValue (IServiceProvider serviceProvider)
{
if (Source == null)
return null;
// Do your translation lookup here, using whatever method you require
var imageSource = Forms9Patch.ImageSource.FromMultiResource(Source);
return imageSource;
}
}
Once you have the above, you can load your embedded resource images as shown in the below example. Be sure to add a namespace for the assembly that contains both your MarkupExtension and your EmbeddedResources (local in the below example).
<?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:local="clr-namespace:MyXamlDemo;assembly=MyXamlDemo"
x:Class="MyXamlDemo.MyPage"
Padding="5, 20, 5, 5">
<ScrollView>
<ScrollView.Content>
<StackLayout>
<Label Text="Xamarin.Image"/>
<Image Source="{local:ImageMultiResource Forms9PatchDemo.Resources.image}"/>
</StackLayout>
</ScrollView.Content>
</ScrollView>
</ContentPage>
Where to learn more
Project page: http://Forms9Patch.com
Nuget page: https://www.nuget.org/packages/Forms9Patch/0.9.1
Demo app repository: https://github.com/baskren/Forms9PatchDemo
Space between Listview cards
I have a listview. What I want is to insert space between the various cards of the listview. How can I achieve this?
Can't kill iOS WKWebView on MainPage change
Say, the MainPage is PageA and PageA has a WKWebView (renderer) in it.
I change the MainPage to PageB which is empty but the WKWebView that belongs to the previous page is still there.
Is there a way to permanently kill the WKWebView and its renderer?
Xamarin forms Maps pin Custom Renderer
protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e)
{
base.OnElementPropertyChanged(sender, e);
if (e.PropertyName.Equals("VisibleRegion") && !isDrawn)
{
NativeMap.Clear();
foreach (var pin in customPins)
{
}
In Android custom renderer ,the below condition never been true and when will it be true?
if (e.PropertyName.Equals("VisibleRegion") && !isDrawn)
and NativeMap.Clear(); NativeMap
always null , So i am not able to add custom pin
Xamarin ListView bug?
Hello. I have a custom listview item which creates instance of HorisontalFilesList control if files provided:
But When i'm scrolling this list a new HorisontalFilesList is appearing. What am i doing wrong?
And the more I scroll the more instances are appearing... But HorizontalFilesList's constructor was called only 3 times (as it should be, because only 3 diagnosis has files).
Code
DiagnosisItem:
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class DiagnosisItem
{
public static BindableProperty FilesProperty = BindableProperty.Create("Files", typeof(List),
typeof(DiagnosisItem), propertyChanged: FilesPropertyChanged);
private readonly Random _random = new Random();
public DiagnosisItem()
{
InitializeComponent();
}
public Color CircleColor => Color.FromRgb(_random.Next(255), _random.Next(255), _random.Next(255));
public List<FileModel> Files
{
get => (List<FileModel>) GetValue(FilesProperty);
set => SetValue(FilesProperty, value);
}
private static void FilesPropertyChanged(BindableObject bindable, object oldValue, object newValue)
{
var items = newValue as List<FileModel>;
var self = bindable as DiagnosisItem;
if (self == null || items == null || items.Count == 0) return;
self.FilesListContainer.Content = new HorizontalFilesList(items);
}
}
HorizontalFilesList:
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class HorizontalFilesList
{
private const int MoreLabelWidth = 83;
public const int Spacing = 11;
public static BindableProperty FilesProperty = BindableProperty.Create("Files", typeof(List),
typeof(HorizontalFilesList), propertyChanged: FilesPropertyChanged);
private List<FileModel> _files;
private bool _isInitialized;
public HorizontalFilesList()
{
InitializeComponent();
}
public HorizontalFilesList(List<FileModel> files) : this()
{
_files = files;
}
public List<FileModel> Files
{
get => (List<FileModel>) GetValue(FilesProperty);
set => SetValue(FilesProperty, value);
}
public int Count => FileList.Children.Count;
private static void FilesPropertyChanged(BindableObject bindable, object oldValue, object newValue)
{
var element = bindable as HorizontalFilesList;
if (element == null) return;
element._files = element.Files;
element._isInitialized = false;
}
protected override SizeRequest OnMeasure(double width, double height)
{
if (_files == null || _isInitialized || _files.Count == 0 || double.IsPositiveInfinity(width))
return base.OnMeasure(width, height);
_isInitialized = true;
if (_files.Count * SmallFileLabel.WidthConstraint + (_files.Count - 1) * FileList.Spacing <= width)
{
// Enough place for all file items
Device.BeginInvokeOnMainThread(() => BuildFileList(_files.Count, _files));
}
else
{
// file items count excluding padding
var count = (int) Math.Round((width - MoreLabelWidth) / SmallFileLabel.WidthConstraint);
// determine items count with spacing
while (count * SmallFileLabel.WidthConstraint + (count - 1) * FileList.Spacing > width) count--;
Device.BeginInvokeOnMainThread(() =>
{
BuildFileList(count, _files);
AddMoreLabel(_files.Count - count);
});
}
return base.OnMeasure(width, height);
}
private void BuildFileList(int count, IReadOnlyList<FileModel> files)
{
for (var index = 0; index < count; index++)
FileList.Children.Add(new SmallFileLabel(files[index].Name, files[index].Type));
}
private void AddMoreLabel(int num)
{
// TODO localization
var label = new Label
{
Text = $"+{num} more",
Style = Resources["ShowMore"] as Style
};
label.SetValue(Grid.ColumnProperty, 1);
Grid.Children.Add(label);
}
}