How change programatically add one and remove another (in other words) make a replace of one class to another?
Dynamic change StyleClass for VisualElement
Ble does not scan when run
Previously, I added code using the plugin Bluetooth LE plugin for Xamarin to scan for ble devices. It had worked for a while but I have since updated to the latest version of Xamarin and Visual Studio, now it just returns with 0 devices in the list. I am compiling using android version 8.1. Is there an issue with my code or an update issue?
using System;
using Android.App;
using Android.Content.PM;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.OS;
using Plugin.BLE;
using Plugin.BLE.Abstractions.Exceptions;
using System.Collections.Generic;
using Android.Bluetooth;
using Whale_Watch.Droid;
namespace Whale_Watch.Droid
{
[Activity(Label = "BLE_Test", Theme = "@style/MainTheme", MainLauncher = true, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation)]
public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity
{
protected async override void OnCreate(Bundle bundle)
{
TabLayoutResource = Resource.Layout.Tabbar;
ToolbarResource = Resource.Layout.Toolbar;
base.OnCreate(bundle);
global::Xamarin.Forms.Forms.Init(this, bundle);
LoadApplication(new App());
await scanAsync();
}
public async System.Threading.Tasks.Task scanAsync()
{
List<Plugin.BLE.Abstractions.Contracts.IDevice> deviceList = new List<Plugin.BLE.Abstractions.Contracts.IDevice>();
var ble = CrossBluetoothLE.Current;
var adapter = CrossBluetoothLE.Current.Adapter;
var state = ble.State;
ble.StateChanged += (s, e) =>
{
};
adapter.DeviceDiscovered += (s, a) => deviceList.Add(a.Device);
await adapter.StartScanningForDevicesAsync();
}
}
}
Exception throws when saving file in Android device in ExternalStorageDirectory
I faced a problem when saving file in the Android device in external storage location.
Xamarin.Forms Android project details:
Target Framework : Android 8.1
Minimum Android version: Android 4.4
Target Android version: Android 8.1
When creating file in the location “Android.OS.Environment.ExternalStorageDirectory” results in exception that the file not found. I also enabled Read and Write external storage permissions in AndroidManifest.xml.
If I changed the Target Android version as “Use Compile Using SDK version”, it working fine.
Can you please let me know why this problem occurs when running application in above mentioned target Android version ?
Entry with secure field text is getting cleared before editing
Hi Guys,
I am trying to develop an application using xamarin forms. it have login screen.
I have an Entry with secure field text is getting cleared before editing.
I Made textField.clearsOnBeginEditing = NO; in App Delegates, still the problem was persist.
Can anyone help on this.
Thanks
How to get the width and height of a frame view for xamarin forms for iOS?
I have implemented a gradient background color for frame and grid view.Its perfectly working fine in android but in iOS i have to mention the width and height static.
mainView = new UIView(new CGRect(0, 0, viewWidth, viewHeight));
i need to get the appended frame height and width but not the default screen size UIScreen.MainScreen.Bounds.Width.
VideoPlayer xamarin forms
Hi xamarin forum
Can anyone give a suggestion where can I find a video player that
1. Can play my video from database using file path
2. can really work on both iOS and Android
I said the number 2 because I am currently using the sample code that is written here
https://developer.xamarin.com/samples/xamarin-forms/customrenderers/VideoPlayerDemos/
but when I tried in my iOS device it crashes my app but when I use it in my Android device all works fine @BillyLiu (Thanks for all the help dude! Cheers!)
[Xamarin.Forms] : How to save ContentPage UI as a PDF and Print.
I want to design a Layout and Print it on A4 page.
So, How do I save Content Page as a PDF and Fire it on Network Printer.
Platforms:
Android
UWP
IOS
I am unable to set the particular page in Carousel view
Hi, I am implemented the Carousel view using https://blog.xamarin.com/flip-through-items-with-xamarin-forms-carouselview/. And I am able to implement the Carousel,
**But My Problem I want to set the startup page while opening (I mean when page is loaded the carousel view should show 5th page or 4th index) **
Plugin Used
Xamarin.Forms.CarouselView (2.3.0-pre2)
What I tried
Case 1: I have used Data binding in xaml but it always showing first page or index of zero
Case 2: I have used Data binding from .cs file like CarouselView.ItemSource= Images; and CarouselView.Position=5; but is giving unhandled exception i.e, System.DivideByZeroException: Attempted to divide by zero.
Here is the Sample code
Case 1:
<cv:CarouselView Position="{Binding Position, Mode=TwoWay}" ItemSelected="CarouselAlbumItems_ItemSelected" ItemsSource="{Binding AlbumItems}" x:Name="CarouselAlbumItems">
<cv:CarouselView.ItemTemplate>
<DataTemplate>
<Grid VerticalOptions="FillAndExpand" HorizontalOptions="FillAndExpand">
<Grid.RowDefinitions>
<RowDefinition Height="*"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<Image x:Name="imgAlbumItemName" Grid.RowSpan="2" Aspect="AspectFit" IsVisible="{Binding IsImage}" >
<Image.Source>
<UriImageSource Uri="{Binding AlbumItemPath}" CacheValidity="14" />
</Image.Source>
</Image>
</Grid>
</DataTemplate>
</cv:CarouselView.ItemTemplate>
</cv:CarouselView>
Case 2:
protected override void OnAppearing()
{
base.OnAppearing();
CarouselAlbumItems.ItemsSource = selectedItem.AlbumItems;
CarouselAlbumItems.Position = position;
}
Error: The name AuthenticationState does not exist in the current context
I am doing google signin for my project . I am getting this error: 'The name AuthenticationState does not exist in the current context' in the MainActivity.cs page .Please see the attached screenshot. will it be removed by adding some libraries? How to solve this error?
Xamarin Forms Android showing Tabbed Page inside Master Details Page is showing blank empty screen
In my Xamarin Forms
application I am having Tabbed Page
as first Detail page
of Master Details Page
. So, while running my Droid
application it is showing empty
blank screen for few seconds and after that it is showing the correct Tabbed Page
. However, if I run the same project in iOS
it is not showing any Empty
or blank
screen; Tabbed page is rendering fast.
What I have tried
If I set any other normal Content Page
as first Detail page
instead of Tabbed Page
means that page is rendering fast in Droid
and also I have tried after updating the Xamarin.Forms
from v2.5.1.444934 to v3.1.0.697729 but no luck.
So, I confirmed that the Empty or Blank
screen is showing in Droid App
for few seconds because of Tabbed Page
. Is there any work around to resolve the problem. Thanks in advance.
Phoneword example: encapsulate Xamarin.Forms don't work for Android.
Hi, I'm very new to C# and Xamarin, so please excuse me.
I'd like to encapsulate the Xamarin.Forms methods from the MainPage into an own Forms.cs.
The UWP works fine, but the Android project freeze and don't show the DisplayAlert.
I have adaptet the Phoneword example from www. developer.xamarin.com/samples/xamarin-forms/Phoneword/
MainPage.xaml.cs
using System;
namespace Phoneword
{
public partial class MainPage
{
Forms forms = new Forms();
async void OnCall(object sender, EventArgs e)
{
if (await forms.FormsDisplayAlert( // Here the Android project freeze and dont show the DisplayAlert
"Dial a Number",
"Would you like to call " + translatedNumber + "?",
"Yes",
"No"))
{
var dialer = forms.GetDependencyService();
if (dialer != null)
dialer.Dial(translatedNumber);
}
}
}
}
Forms.cs
using System.Threading.Tasks;
using Xamarin.Forms;
namespace Phoneword
{
public class Forms : ContentPage
{
public Task<bool> FormsDisplayAlert(string title, string message, string accept, string cancel)
{
return DisplayAlert(title, message, accept, cancel);
}
public IDialer GetDependencyService()
{
return DependencyService.Get<IDialer>();
}
}
}
I am very grateful for any help.
Type mismatch on Bindableproperty
Hi,
I have following codes in my custom view class and xaml files:
my custom property:
public static readonly BindableProperty LabelColorProperty = BindableProperty.CreateAttached("LabelColor", typeof(Color), typeof(InfoCell), Color.White,
propertyChanged: HandleLabelColorChange);
public static Color GetLabelColor(BindableObject target) {
return (Color)target.GetValue(LabelColorProperty);
}
public static void SetLabelColor(BindableObject target, Color value) {
target.SetValue(LabelColorProperty, value);
}
private static void HandleLabelColorChange(BindableObject bindable, object oldValue, object newValue){
//here i do stuff
}
my xaml tag:
<ce:InfoCell DescriptionText="{Binding DetailCount}" LabelColor="{StaticResource primaryTextColor}"/>
my static resource in App.xaml
<Color x:Key="primaryTextColor">White</Color>
When i pass a color property to LabelColor like White, Black etc. everything is ok. But when i pass a static resource like above
a compile time error occurs like
No property, bindable property, or event found for 'LabelColor', or mismatching type between value and property...
So, what am i missing?
Thanks in advence..
I want to increase the size of my FontAwesome icons
I am currently testing on Android.
I want to put a FA icon in my button but when it appears it is far too small. So I try to set a FontSize style, but this does not make any difference. What am I doing wrong here?
<?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:controls="clr-namespace:XamForms.Controls;assembly=XamForms.Controls.Calendar"
xmlns:Control="clr-namespace:Xamstrap;assembly=Xamstrap"
xmlns:Attached="clr-namespace:Xamstrap.AttachedProperties;assembly=Xamstrap"
xmlns:c="clr-namespace:Sir.Mobile.CustomRenderers"
xmlns:prism="clr-namespace:Prism.Mvvm;assembly=Prism.Forms"
prism:ViewModelLocator.AutowireViewModel="True"
x:Class="Sir.Mobile.Views.InspectionDate"
ControlTemplate="{StaticResource MainHeader}"
Title="Inspection Date">
<ContentPage.Resources>
<OnPlatform x:Key="FontAwesomeString" x:TypeArguments="x:String">
<On Platform="iOS" Value="FontAwesome" />
<On Platform="Android" Value="FontAwesome.ttf#FontAwesome" />
<On Platform="UWP, WinRT, WinPhone" Value="Assets/Fonts/FontAwesome.ttf#FontAwesome" />
</OnPlatform>
<Style x:Key="FontAwesome" TargetType="Button">
<Setter Property="FontFamily" Value="{StaticResource FontAwesomeString}" />
<Setter Property="FontSize" Value="50" />
</Style>
<!-- Can now use style sheets, see https://docs.microsoft.com/en-us/xamarin/xamarin-forms/user-interface/styles/css/index -->
<StyleSheet Source="/Assets/Site.css" />
</ContentPage.Resources>
<ContentPage.Content>
<StackLayout Orientation="Vertical" HorizontalOptions="StartAndExpand">
<Label Text="{Binding HeaderTitle3}" StyleClass="headerText" Margin="0, 0, 0, 0"></Label>
<StackLayout Orientation="Horizontal">
<StackLayout>
<controls:Calendar SelectedDate="{Binding DateOfVisit, Mode=TwoWay}"
HorizontalOptions="FillAndExpand" VerticalOptions="CenterAndExpand"
x:Name="calendar" DateCommand="{Binding DateOfVisitCommand}" />
</StackLayout>
<StackLayout>
<Button Command="{Binding OnDateOfVisitCommand}" Style="{Binding FontAwesome}"
Text="" Attached:ResponsiveProperty.Class="btn-sm btn-primary" ></Button>
</StackLayout>
</StackLayout>
</StackLayout>
</ContentPage.Content>
</ContentPage>
HOW TO ACCESS THE FILE PATH IN IOS DEVICE
Hi,
I'm working for download/upload files like image, docs and video in Xamarin.Forms IOS. I use PCLStorage from Nuget. My question is that how can I access the filepath like this:
this path is on my emulator in Mac:
/Users/mac-name/Library/Developer/CoreSimulator/Devices/138067AE-00A4-4B9B-BCDA-15133F13A/data/Containers/Data/Application/850D57E6-50AD-40D0-A5E3-30745C21/Documents/../Library/ImageTest
I've see the image save in this path in imac folder.
this path is in my iphone:
/var/mobile/Containers/Data/Application/9B119CB1-47AD-49B9-80B3-7228D52C/Documents/../Library/ImageTest
I want also to see this in folder files/ or File Manager in Iphone like android.
If anyone of you guys who already tried this or any best way to fix my issue please give some advice.
Thanks in advance!
Xamarin.Forms - Can't get geolocation
Hi,
I am trying to use the code from this article:
https://docs.microsoft.com/en-us/xamarin/essentials/geolocation?tabs=android
but "using Xamarin.Essentials" leads to compile-time error:
Error CS0234 The type or namespace name 'Essentials' does not exist in the namespace 'Xamarin' (are you missing an assembly reference?) AndroidXamarinWIFIApp1 C:\prj\Demo\AndroidXamarinWIFIApp1\AndroidXamarinWIFIApp1\MainPage.xaml.cs
What assembly should I add to get rid of this error?
listView binding
How to Bind the ListView with an Observablecollection type where the type itself an observable collection.
My MVVM like below
ViewModel
public class OrdersViewModel
{
public ObservableCollection<Order> Orders{ get; set; }
public OrdersViewModel()
{
Orders = new ObservableCollection<Order> { new Order(),new Order(),new Order()};
}
}
Models:
public class Order:INotifyPropertyChanged
{
public ObservableCollection<OrderItem> OrderItems { get; set; }
public Order()
{
OrderItems = new ObservableCollection<OrderItem> { new OrderItem("xxxx", "2", "200"),
new OrderItem("yyyy", "1", "500"),
new OrderItem("zzzz", "1", "400")
};
OrderId =( new Guid()).ToString();
}
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged(string propertyName)
{
var changed = PropertyChanged;
if(changed != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}
public class OrderItem
{
public string OrderITemName { get; set; }
public string Units { get; set; }
public string UnitPricePerItem { get; set; }
public OrderItem(string _orderITemName,string _units,string _unitPricePerItem)
{
OrderITemName = _orderITemName;
Units = _units;
UnitPricePerItem = _unitPricePerItem;
}
}
View
<ContentPage.BindingContext>
<local:OrdersViewModel />
</ContentPage.BindingContext>
<ContentPage.Content>
<StackLayout>
<ListView x:Name="OrdersListView" ItemsSource="{Binding Orders}" >
<ListView.ItemTemplate >
<DataTemplate >
<ViewCell>
<StackLayout>
<Label x:Name="OrderITemName" Text="{Binding OrderITemName}" />
<Label x:Name="Units" Text="{Binding Units}" />
<Label x:Name="UnitPricePerItem" Text="{Binding UnitPricePerItem}" />
</StackLayout>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</StackLayout>
</ContentPage.Content>
where we using task async and await method in xamarin forms ?
Hello guys can you describe me where we are using task async and await method in xamarin forms ?
Apk size is too large.How to reduce it?
In my xamarin form application I am using Telerik.but when I release my apk for playstore,the apk size taking 86 mb..so how to reduce it?
I checked all linking setting,while using sdk and user assembly,and sdk assembly only then apk not open.
how to solve this?
Dependency Injection best practice ?
I am trying to use Dependency Injection in my project but its still new to me. I've read quite a lot of tutorials but I still don't what is the best practice to create pages or viewmodels..
It seems like everyone is saying, that Service Locator is a bad practice or "anti-pattern" and then they still proceed to do something like this inside of code behind:
_viewModel = IocContainer.Resolve<SomeViewModel>();
Isn't that killing purpose of IoC ?
I have been suggested to inject view model in page's constructor and then instantiate it somewhere else with factory. I should also mention, that I want to pass a parameter to a view model (apart from other injected services).
I'll give you example:
// Order detail
public class OrderDetailViewModel : BaseViewModel
{
public Order Order { get; set; }
public ICommand UpdateOrderCommand => new Command(UpdateOrder);
// I just made that up, so I have at least one service in a constructor
// because it makes things more complicated for me (but I need it), when I have something, that is injected (order manager)
// along with something, thats is passed (order)
private readonly IOrderManager _orderManager;
public OrderDetailViewModel(Order order, IOrderManager orderManager)
{
Title = "Detail";
Order = order;
_orderManager = orderManager;
}
private void UpdateOrder()
{
_orderManager.Update(Order);
}
}
// This class holds list of orders and when I click on some order, order detail is displayed so I have to pass that order to an orderdetail view model
public class OrdersViewModel : BaseViewModel
{
public ObservableCollection Orders { get; set; }
public ICommand SelectOrderCommand => new Command(async (orderInfo) => await SelectOrder(orderInfo));
private readonly IApiService _apiService;
private readonly INavigationService _navigation;
private readonly IViewModelFactory _factory;
// These services are injected as I would expect
public OrdersViewModel(INavigationService navigation, IApiService apiService, IViewModelFactory factory)
{
Title = "Orders";
Orders = new ObservableCollection<OrderRowDto>();
_navigation= navigation;
_apiService = apiService;
_factory = factory;
}
private async Task SelectOrder(OrderRowDto orderInfo)
{
var order = await _apiService.GetOrderAsync(orderInfo.Id);
// THIS IS WHERE I AM UNSURE. IF ITS OK TO DO IT THIS WAY
var viewModel = _factory.CreateOrderDetailViewModel(order);
await _navigation.PushAsync(new OrderDetailPage(viewModel));
}
}
//Factory
public class ViewModelFactory : IViewModelFactory
{
// this will be injected
private readonly IOrderManager _orderManager;
public ViewModelFactory(IOrderManager orderManager)
{
_orderManager = orderManager;
}
public OrderDetailViewModel CreateOrderDetailViewModel(Order order)
{
return new OrderDetailViewModel(order, _orderManager);
}
}
So I removed creation of view model from code behind, because this
_viewModel = IocContainer.Resolve<OrderDetailViewModel>();
would not allow me to pass that "Order" in constructor.
I know I could add this, If I would passed that order in page's constructor
_viewModel.Order = Order;
but it doesnt seems very nice.
So my question is, if that approach with factory is a good idea or not..
Because I dont want it to backfire later on
I was also wondering, if creating pages manually (new OrderDetailPage(..)) is good practice as well when attempting to use DI
Thank you. (sorry about code formating.. `` doesnt seems to do, what I want it to do)
How to add json layer in a button click in xamarin forms?
I am new in xamarin forms I want to add a json layer in a button click in my map.How can I do this.I am tried with a dependency for adding json layer.I using using Xamarin.Forms.GoogleMaps for creating map.
Please help me...
Here is my code
private void Close_Tapped(object sender, EventArgs e)
{
try
{
var _IIGeoJsonLayer = DependencyService.Get<IGeoJsonLayer>();
_IIGeoJsonLayer.AddLayerJson();
}
catch (Exception ex)
{
}
}
Here is my Dependency Service
public void AddLayerJson()
{
GoogleMap gmap =null;
GeoJsonLayer layer = new GeoJsonLayer(gmap, Resource.Raw.jsonFile, Android.App.Application.Context);
layer.AddLayerToMap();
}