Quantcast
Channel: Xamarin.Forms — Xamarin Community Forums
Viewing all 91519 articles
Browse latest View live

(Android) Force every page on portrait except one which could be portrait or landscape

$
0
0

Hello,

I am trying to achieve the following :

On tablet, the orientation should be allowed to both portrait or landscape whenever the user wants

On Phone, the orientation should be forced to portrait except on the gallery which is one single view, where both orientation are allowed.

On iOS, this works fine, but on Android, that's harder to get.

The first thing I tried is to use the OnConfigurationChange event, adding the flags :

       ConfigurationChanges =  ConfigChanges.Orientation | ConfigChanges.ScreenSize

In the MainActivity.

However, by doing that, when I set the requestedOrientation, the event isn't triggered anymore.

Then I focused on some post I saw which indicate that the MessagingCenter is needed. So that's what I tried :

On the MainActivity :

        if (Device.Idiom == TargetIdiom.Phone)
        {
            RequestedOrientation = ScreenOrientation.Portrait;

            MessagingCenter.Subscribe<Gallery>(this, "AllowLandscape", sender =>
            {
                RequestedOrientation = ScreenOrientation.Landscape;
            });

            MessagingCenter.Subscribe<Gallery>(this, "PreventLandscape", sender =>
            {
                RequestedOrientation = ScreenOrientation.Portrait;
            });
        }

And then I allowed LandScape by sending the message in the Gallery OnAppearing, but it forces the orientation to Landscape where I want it to be free.

Then I sent the PreventLanscape message OnDisappearing

Okay that almost did the trick, and I could eventually say to the customer that the easier is to force Landscape on the gallery.

The things are that using that also "repainted" views from NavigationStack and that some pictures are now on Landscape Format and not Portrait even if OnDisappearing I sent the message to set it back to Portrait.

So here is my question : Whats the good way to deal with this problem ? Is it even possible ?

Some infos : Using Xam Forms 4.5.0.396 / Essentials 1.5.1


Custom TimeControler doesnt work while add from code Behind on ios

$
0
0

Hi, I am struggling with a stupid problem, I have made a custom TimePicker for Ios, it works perfectly when it is added in xaml

 <customControls:CustomTimePicker
                        x:Name="EndHour"
                        Grid.Row="9"
                        Grid.Column="1"
                        Focused="MyEndTimePicker_Focused"
                        Format="HH:mm"
                        HorizontalOptions="FillAndExpand"
                        PropertyChanged="ChangedEndHour"
                        PropertyChanging="OldChangedEndHour"
                        Style="{StaticResource MainTimeStyle}"
                        Time="{Binding EndHour}" />

but when I add this control form code behind

var leftTimePicker = new CustomTimePicker { HorizontalOptions = LayoutOptions.Center };
                var rightTimePicker = new CustomTimePicker { HorizontalOptions = LayoutOptions.Center };
                var rowToChange = MainGrid.RowDefinitions.ElementAt(RowNumber);

                var finalHeight = rowToChange.Height.Value + RowHeight;

                rowToChange = new RowDefinition { Height = new GridLength(finalHeight, GridUnitType.Star) };

                MainGrid.RowDefinitions[RowNumber] = rowToChange;

                var label = new Label { TextColor = Color.Blue };

                switch (dayPrior.Key)
                {
                    case "Mon":
                        label.Text = "Poniedziałek";
                        leftTimePicker.SetBinding(CustomTimePicker.TimeProperty, "MonStartHour");
                        rightTimePicker.SetBinding(CustomTimePicker.TimeProperty, "MonEndHour");
                        break;

This is my custom picker

 public class CustomTimePickerRenderer : TimePickerRenderer
    {
        protected override void OnElementChanged(ElementChangedEventArgs<TimePicker> e)
        {
            base.OnElementChanged(e);

            if (Control != null)
            {
                var timePicker = (UIDatePicker)Control.InputView;
                timePicker.Locale = new NSLocale("no_nb");

                if (Element != null && !Element.Time.Equals(default(TimeSpan)))
                    Control.Text = Element.Time.ToString(@"hh\:mm");
                else
                    Control.Text = DateTime.Now.ToString("HH:mm");
            }
        }      
    }

How to draw a half filled star in Skiasharp?

$
0
0

I try to create star with skiasharp.extended. it works perfectly fine with code below but I would like to fill it not fully. Either half or even better based on percentage. so if fully filled star is 100%, can i fill it only like 25%

   void SkCanvasViewRequiredPainting(object sender, SKPaintSurfaceEventArgs args)
        {
            SKImageInfo info = args.Info;
            SKSurface surface = args.Surface;
            SKCanvas canvas = surface.Canvas;

            canvas.Clear();

            SKPaint paint = new SKPaint
            {
                Style = SKPaintStyle.Stroke,
                Color = Color.Red.ToSKColor(),
                StrokeWidth = 10
            };

            canvas.DrawStar(
                100, 100, // x, y
                100,      // outer radius
                40,       // inner radius
                5, paint);       // points

            paint.Style = SKPaintStyle.Fill;
            paint.Color = SKColors.Blue;
            paint.IsAntialias = true;
            paint.IsAutohinted = true;
            paint.HintingLevel = SKPaintHinting.Slight;

            canvas.DrawStar(
                100, 100, // x, y
                100,      // outer radius
                40,       // inner radius
                5, paint);       // points

        }

ProGuard Problem

$
0
0

Hello, I'm having a problem when generating the apk file. This happens when I activate the proGuard. What I've done so far:

  • Reinstalling the SDK files;
  • Downloading the latest proGuard and updating the folder;

What is weird is that in a new project I don't have this problem. But in the project I'm working I have this issue, so maybe is something related to the project and not the interface. I an still a newbie to Xamarin and C# and I'm learning on the go. I thought about recreating the project, but I don't now the proper way to do it. I know I probably didn't get the necessary info in the question but please let me know what information is required.

Thanks a lot.

[iOS] How to remove UIWebVIew references without using Link All and mtouch arguments? App crashes

$
0
0

Hello! I want to remove old UIWebView deprecation from application to publish in AppStore, but it seems every option (Link only sdk/Link all + mtouch arguments provided here: https://docs.microsoft.com/en-us/xamarin/xamarin-forms/user-interface/webview?tabs=macos#configure-the-linker-preview ) results in app crash.

I honestly don't have resources or time to find every small error in every library that conflicting with linker, fire pull requests for them to fix linker errors etc. I'm kinda ok with the app size being bigger than without linker, but I need to get rid of reference to the old UIWebView, because my apps won't be published in the AppStore starting April 2020 if I won't remove UIWebVIew references.

Library MIDI or similar instructional apps

$
0
0

Hello:
Is there any MIDI library or others to develop apps for instructional music, free if possible, for Xamarin Forms.
Or what do you suggest me?
thank you very much

Gif animation while pushing a page

$
0
0

Hello everybody.

I've asked this question 2 times and got no answer, I really need help with this so if anybody has any suggestion I will be glad to hear it.
So my problem is that I am pushing a PopUp page with this plugin https://github.com/rotorgames/Rg.Plugins.Popup with an Image which has a gif as source.
I push that popup and then I create the instance of another page and push it to navigation stack, then I remove the popup from the Popup stack.
The problem is that while it is loading the page (not the popup but the normal page) the gif stops (since PushAsync locks UI).

Any suggestion?

Thank You.
P.D.: Original post with more info: https://forums.xamarin.com/discussion/179413/load-a-popup-page-with-a-gif-while-pushing-a-page-stops-its-movement#latest

Using with Facebook login in xamarin form

$
0
0

I Use Xamarin.Auth for login with Facebook Account, Facebook'sProfile photo Resolution is not clear in my App.

private void FacebookClicked(object sender)
{
PublicClass.LocalStorage.ClearAllStorage();
Helper.Constants.AuthSignUp = 1;
Helper.Settings.GeneralUserType = "";
DependencyService.Get().facebook();
}

**Dependency Service **

public class FacebookAuth : BaseViewModel, IFacebook
{
public void facebook()
{
var auth = new OAuth2Authenticator(
clientId: "1106049452932664",
scope: "email",
authorizeUrl: new System.Uri("https://m.facebook.com/dialog/oauth"),
redirectUrl: new System.Uri("https://www.facebook.com/connect/login_success.html"));

        auth.Completed += Auth_Completed;
        var ui = auth.GetUI((Activity)Forms.Context);
        ((Activity)Forms.Context).StartActivity(ui);
    }

    private async void Auth_Completed(object sender, AuthenticatorCompletedEventArgs e)
    {
        if (e.IsAuthenticated)
        {
            UserDialogs.Instance.ShowLoading();
            var request = new OAuth2Request(
                                            "GET",
                                            new System.Uri("https://graph.facebook.com/me?fields=email,name,first_name,last_name,gender,picture"),//https://graph.facebook.com/me?fields=name,picture,cover,birthday //https://graph.facebook.com/me?fields=email,name,first_name,last_name,gender,picture
                                            null,
                                            e.Account);

            var fbResponse = await request.GetResponseAsync();

            //var fbUserAccessToken = CrossFacebookClient.Current.ActiveToken;
            var obj = JObject.Parse(fbResponse.GetResponseText());
            var email = string.Empty;
            try
            {
                email = obj["email"].ToString().Replace("\"", "");
            }
            catch (Exception ex)
            {
                email = "psycho@gmail.com";
            }
            var FacebookAccessToken = e.Account.Properties["access_token"];
            var json = fbResponse.GetResponseText();
            var fbUser = JsonConvert.DeserializeObject<FacebookUserModel>(json);
            var name = fbUser.name;
            Helper.Constants.AuthUserEmail = email;
            Helper.Constants.AuthUserFName = fbUser.name;
            Helper.Constants.AuthUserLName = fbUser.last_name;
            Helper.Constants.AuthUserPhone = string.Empty;
            Helper.Constants.AuthUserProfilePic = fbUser.picture.data.url;
            Xamarin.Forms.MessagingCenter.Send<string>(Convert.ToString(Helper.Constants.isAuthLogin), "AuthLogin");
        }
    }
}

Is it possible to call an asynchronous method from a synchronous method?

$
0
0

Hello everyone,

I'm having a Xamarin.forms application and what I'm trying to do is:
1) someone clicks on an item in a listview
2) the application shows a dialog to the user
3) the application waits until the user has pressed "yes" or "no"
4) as soon as there's input from the user, the application (code) continues again

I know that normally it's possible to make your method async and then apply an await on the DisplayAlert. However, because the code is so enormous, changing the method to async has a lot of effect on the rest of my code.. So I wondered if it's possible to call/await an asynchronous method from a synchronous method?

To show the dialog, I use the following code:

private async Task<bool> ShowDialog()
{
return await DisplayAlert("Question?", "Waiting for user input", "Yes", "No");
}

And to await the message box I use the following the code:

public void SyncMethod()
{
// Showing the listview here
// The user clicks an item
bool result = await ShowDialogAsync();

// after the user has clicked something,
// then continue with more code here.
if (result)
// Result = true
}

Unfortunately the SyncMethod needs to be async. Is there a way to solve this without making this method async? Thanks for the answer :)

Getting "System.IO.DirectoryNotFoundException: Could not find a part of the path" after update

$
0
0

Today i installed the recent updates for visual studio and others like xamarin.android and / .ios
And im getting this error now, and i don't know what to do...
Any advice? Thanks very much!

Error XA0000: Unhandled exception: System.IO.DirectoryNotFoundException: Could not find a part of the path "/Users/eduardoneto/PROJETOS/myapp/myapp.Droid/obj/Debug/lp/78/jl/res/**/*.png".

Full error:
/Library/Frameworks/Mono.framework/External/xbuild/Xamarin/Android/Xamarin.Android.Common.targets(2,2): Error XA0000: Unhandled exception: System.IO.DirectoryNotFoundException: Could not find a part of the path "/Users/eduardoneto/PROJETOS/myapp/myapp.Droid/obj/Debug/lp/78/jl/res/**/*.png".
at System.IO.FileStream..ctor (System.String path, System.IO.FileMode mode, System.IO.FileAccess access, System.IO.FileShare share, System.Int32 bufferSize, System.Boolean anonymous, System.IO.FileOptions options) [0x0015e] in /Users/builder/jenkins/workspace/build-package-osx-mono/2019-10/external/bockbuild/builds/mono-x64/mcs/class/corlib/System.IO/FileStream.cs:223
at System.IO.FileStream..ctor (System.String path, System.IO.FileMode mode, System.IO.FileAccess access, System.IO.FileShare share, System.Int32 bufferSize, System.IO.FileOptions options) [0x00000] in /Users/builder/jenkins/workspace/build-package-osx-mono/2019-10/external/bockbuild/builds/mono-x64/mcs/class/corlib/System.IO/FileStream.cs:106
at (wrapper remoting-invoke-with-check) System.IO.FileStream..ctor(string,System.IO.FileMode,System.IO.FileAccess,System.IO.FileShare,int,System.IO.FileOptions)
at System.IO.FileSystem.CopyFile (System.String sourceFullPath, System.String destFullPath, System.Boolean overwrite) [0x00025] in /Users/builder/jenkins/workspace/build-package-osx-mono/2019-10/external/bockbuild/builds/mono-x64/external/corefx/src/System.IO.FileSystem/src/System/IO/FileSystem.Unix.cs:54
at System.IO.File.Copy (System.String sourceFileName, System.String destFileName, System.Boolean overwrite) [0x00056] in /Users/builder/jenkins/workspace/build-package-osx-mono/2019-10/external/bockbuild/builds/mono-x64/external/corefx/src/System.IO.FileSystem/src/System/IO/File.cs:74
at System.IO.File.Copy (System.String sourceFileName, System.String destFileName) [0x00000] in /Users/builder/jenkins/workspace/build-package-osx-mono/2019-10/external/bockbuild/builds/mono-x64/external/corefx/src/System.IO.FileSystem/src/System/IO/File.cs:56
at Xamarin.Android.Tools.Files.CopyIfChanged (System.String source, System.String destination) [0x00033] in :0
at Xamarin.Android.Tasks.MonoAndroidHelper.CopyIfChanged (System.String source, System.String destination) [0x00000] in :0
at Xamarin.Android.Tasks.Crunch.DoExecute (System.Linq.IGrouping2[TKey,TElement] imageGroup) [0x00095] in <e29c048b3b5443a3a8a19c4ed24d3a3a>:0 at Xamarin.Android.Tasks.AsyncTaskExtensions+<>c__DisplayClass0_11[TSource].b__0 () [0x00000] in :0 (XA0000) (myapp.Droid)

my vs versions:

=== Visual Studio Community 2019 for Mac ===

Version 8.5 (build 3183)
Installation UUID: cae51bb2-5449-434c-a2e8-1562ce0250f5
GTK+ 2.24.23 (Raleigh theme)
Xamarin.Mac 6.14.1.39 (d16-5 / 30e8706b4)

Package version: 608000123

=== Mono Framework MDK ===

Runtime:
Mono 6.8.0.123 (2019-10/1d0d939dc30) (64-bit)
Package version: 608000123

=== Roslyn (Language Service) ===

3.5.0-beta4-20125-04+1baa0b3063238ed752ad1f0368b1df6b6901373e

=== NuGet ===

Version: 5.4.0.6315

=== .NET Core SDK ===

SDK: /usr/local/share/dotnet/sdk/3.1.200/Sdks
SDK Versions:
3.1.200
3.1.102
3.1.101
3.1.100
3.0.101
3.0.100
2.1.701
MSBuild SDKs: /Library/Frameworks/Mono.framework/Versions/6.8.0/lib/mono/msbuild/Current/bin/Sdks

=== .NET Core Runtime ===

Runtime: /usr/local/share/dotnet/dotnet
Runtime Versions:
3.1.2
3.1.1
3.1.0
3.0.1
3.0.0
2.1.16
2.1.15
2.1.14
2.1.13
2.1.12

=== Xamarin.Profiler ===

Version: 1.6.12.26
Location: /Applications/Xamarin Profiler.app/Contents/MacOS/Xamarin Profiler

=== Updater ===

Version: 11

=== Apple Developer Tools ===

Xcode 11.3.1 (15715)
Build 11E146

=== Xamarin.Mac ===

Version: 6.14.1.39 (Visual Studio Community)
Hash: 30e8706b4
Branch: d16-5
Build date: 2020-02-20 16:41:47-0500

=== Xamarin.Android ===

Version: 10.2.0.100 (Visual Studio Community)
Commit: xamarin-android/d16-5/988c811
Android SDK: /Users/afonsopereira/Library/Developer/Xamarin/android-sdk-macosx
Supported Android versions:
7.1 (API level 25)
8.0 (API level 26)
8.1 (API level 27)

SDK Tools Version: 26.1.1
SDK Platform Tools Version: 29.0.6
SDK Build Tools Version: 29.0.2

Build Information:
Mono: c0c5c78
Java.Interop: xamarin/java.interop/d16-5@fc18c54
ProGuard: xamarin/proguard/master@905836d
SQLite: xamarin/sqlite/3.28.0@46204c4
Xamarin.Android Tools: xamarin/xamarin-android-tools/d16-5@9f4ed4b

=== Microsoft Mobile OpenJDK ===

Java SDK: /Users/afonsopereira/Library/Developer/Xamarin/jdk/microsoft_dist_openjdk_1.8.0.25
1.8.0-25
Android Designer EPL code available here:
https://github.com/xamarin/AndroidDesigner.EPL

=== Android SDK Manager ===

Version: 16.5.0.39
Hash: 6fb4c79
Branch: remotes/origin/d16-5
Build date: 2020-02-20 23:25:56 UTC

=== Android Device Manager ===

Version: 16.5.0.71
Hash: 49194e8
Branch: remotes/origin/d16-5
Build date: 2020-02-20 23:26:18 UTC

=== Xamarin Designer ===

Version: 16.5.0.471
Hash: 35aa4889d
Branch: remotes/origin/d16-5
Build date: 2020-02-25 00:52:08 UTC

=== Xamarin.iOS ===

Version: 13.14.1.39 (Visual Studio Community)
Hash: 30e8706b4
Branch: d16-5
Build date: 2020-02-20 16:41:48-0500

=== Xamarin Inspector ===

Version: 1.4.3
Hash: db27525
Branch: 1.4-release
Build date: Mon, 09 Jul 2018 21:20:18 GMT
Client compatibility: 1

=== Build Information ===

Release ID: 805003183
Git revision: 60e06e010baa677204535600661dda3fb4677c2f
Build date: 2020-03-20 06:18:03-04
Build branch: release-8.5
Xamarin extensions: 60e06e010baa677204535600661dda3fb4677c2f

=== Operating System ===

Mac OS X 10.15.3
Darwin 19.3.0 Darwin Kernel Version 19.3.0
Thu Jan 9 20:58:23 PST 2020
root:xnu-6153.81.5~1/RELEASE_X86_64 x86_64

Xamaian + Sqlite + Offline + Azur

$
0
0

Hi all togehter,

some time ago i build a spike to test Xamarian, Sqlite OfflieSync and Azure with EasyTable.
As i can readin the Azure Forum Easytable is removed.

a)Is there any idea how to build an app with offline Sync without using Easytable?
b)is there any recommendation in using SQLite + Azure etc.

Thanks in andvance
Peter

MVVM/Prism: Navigate to a page within a TabbedPage and keep ViewModel

$
0
0

I am using Prism and know allready how to navigate to a certain page within my ViewModel:
var result = await NavigationService.NavigateAsync("MyPage?selectedTab=MyPage3");

That works, but I am sharing one ViewModel between all my single pages by setting the BindingContext of each page to "BindingContext = {Binding .,Mode=TwoWay}, which also works perfectly

But: when I navigate to a single Page using Prism, the page loses the instance of the current ViewModel.

I try to achieve this:
Page 1: Filter Data
Page 2: Show Results in a ListView
Page 3: Show Results in a CarouselView
After filtering the Data in Page 1 I want to navigate directly to Page2 or 3

I would be very pleased if someone has any tips to solve that problem...

Converter in DataTemplate

$
0
0

I have a datatemplate in a separate xaml file and I cannot get the converter to work. What needs be done? Thanks.

<?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:viewmodelbase="clr-namespace:MyApp.ViewModel.Base"
             xmlns:viewmodel="clr-namespace:MyApp.ViewModel"
             x:DataType="viewmodel:SharingViewModel"
             x:Class="MyApp.View.SharingPage"
             x:Name="sharingpage"
             Visual="Material" >
    <ContentPage.Resources>
        <viewmodelbase:InverseBoolConverter x:Key="inverter"/>
        <ResourceDictionary Source="DataTemplate\MyViewTemplate.xaml"  />
    </ContentPage.Resources>

    <ContentPage.Content>

        <StackLayout>
             <Button Margin="0,10,0,10" Text="Scan QR Code" BackgroundColor="Orange"
                     WidthRequest="150"  BorderRadius="60" VerticalOptions="Center" 
                     HorizontalOptions="Center"
                    Clicked="OnButtonClicked" >
             </Button>

            <ListView x:Name="DeviceListView" SeparatorVisibility="Default" 
                  HorizontalOptions="FillAndExpand" 
                  VerticalOptions="FillAndExpand" 
                  RowHeight="90" 
                  ItemTapped="OnItemTapped"
                  ItemSelected="OnItemSelected"
                  ItemsSource="{Binding Person}" 
                  ItemTemplate="{StaticResource MyViewTemplate}">

            </ListView>



        </StackLayout>
    </ContentPage.Content>
</ContentPage> 

MyViewTemplate.xaml

<?xml version="1.0" encoding="UTF-8"?>
<?xaml-comp compile="true" ?>
<ResourceDictionary xmlns="http://xamarin.com/schemas/2014/forms"
                    xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
                >



    <DataTemplate x:Key="MyViewTemplate"   >
        <ViewCell>
            <ViewCell.View>
                <StackLayout Margin="2,4,4,4" VerticalOptions="FillAndExpand" >
                    <Frame  Padding="2"  HasShadow="False" BorderColor="LightGray"  CornerRadius="15" IsClippedToBounds="True" VerticalOptions="FillAndExpand">
                        <Grid  Opacity = "{Binding Opacity}" >
                            <Grid.ColumnDefinitions >
                                <ColumnDefinition Width="8"/>
                                <ColumnDefinition Width="*"/>
                                <ColumnDefinition Width="2*"/>
                                <ColumnDefinition Width="*"/>
                            </Grid.ColumnDefinitions>
                            <Grid.RowDefinitions>
                                <RowDefinition Height="0.15*"/>
                                <RowDefinition Height="0.7*"/>
                                <RowDefinition Height="0.15*"/>
                            </Grid.RowDefinitions>
                            <Image Source="{Binding Image}"  Aspect="AspectFit" Grid.Row="1" Grid.Column="1"/>
                            <StackLayout  Grid.Row="1" Grid.Column="2" Grid.ColumnSpan="2" IsVisible="{Binding IsEnable}" >
                                <Label Text="{Binding Name}" VerticalTextAlignment="Center" FontSize="20"   />
                            </StackLayout>
                            <StackLayout  Grid.Row="2" Grid.Column="2" Grid.ColumnSpan="2" IsVisible="{Binding IsEnable, Converter={Resource inverter}  }" >
                                <Label Text="No Found" VerticalTextAlignment="Center" FontSize="20"   />
                            </StackLayout> 
                        </Grid>
                    </Frame>
                </StackLayout>
            </ViewCell.View>
        </ViewCell>
    </DataTemplate>
</ResourceDictionary>

Error Run Project Android 4.3

$
0
0

Severity Code Description Project File Line Suppression State
Error ADB1000: System.ArgumentOutOfRangeException: Length cannot be less than zero.
Parameter name: length
at System.String.Substring(Int32 startIndex, Int32 length)
at Mono.AndroidTools.AndroidInstalledPackage..ctor(String value) in E:\A_work\412\s\External\androidtools\Mono.AndroidTools\AndroidInstalledPackage.cs:line 55
at Mono.AndroidTools.Internal.AdbOutputParsing.ParseLastResortPackageList(String output) in E:\A_work\412\s\External\androidtools\Mono.AndroidTools\Internal\AdbOutputParsing.cs:line 65
at Mono.AndroidTools.AndroidDevice.<>c__DisplayClass68_0.b__0(Task1 t) in E:\A\_work\412\s\External\androidtools\Mono.AndroidTools\AndroidDevice.cs:line 467 at System.Threading.Tasks.ContinuationResultTaskFromResultTask2.InnerInvoke()
at System.Threading.Tasks.Task.Execute() 0

Works higher on Android
I'm testing it on a Huawei handset

Of course later I see that there is a program
But as if the Ajax commands didn't work to get the data

How to get a renderer of a view which is not part of the visual tree?

$
0
0

It is difficult even to formulate the question right. I’ll try to start from what I’m really trying to achieve but it can be rephrased as “Where the renderer is set for a view?”. That might help me to understand what to do with all that. Or “How to attach a renderer to a view?”.
Ultimately, I want to create a ContentView in the code behind with a bunch of controls inside. For the simplicity of the question let’s say it is going to look like this

            var contentView = new ContentView() {
               Content = new Label() {
                  FontSize = 80d,
                  Text = 2.ToString()
               }
            };

Then, I want to render this view into an image without showing that view. I understand I have to create a dependency service interface and its implementation in the platform specific assembly. It seems to me that approximately this code should work for Android.

         IVisualElementRenderer visualElementRenderer = _View.GetRenderer();

         Bitmap bitmap = Bitmap.CreateBitmap((int)_View.Width, (int)_View.Height, Bitmap.Config.Argb8888);
         var canvas = new Canvas(bitmap);

         visualElementRenderer.View.Draw(canvas);

         var stream = new MemoryStream();
         bitmap.Compress(Bitmap.CompressFormat.Png, 90, stream);
         stream.Seek(0L, SeekOrigin.Begin);

         return ImageSource.FromStream(() => stream);

In the result I will get back an image source which then I should be able to use in the Forms to display an image with this image source.
Now, the big problem is GetRenderer returns null. And it seems it will continue returning null until I add the ContentView to the visual tree. I tried that. After that GetRenderer is not null but even then, it does not become not null immediately when I add ContentView to the visual tree. It becomes not null somewhat later. What I would like to do is to find a way how to initialize the renderer on the ContentView without adding it to the visual tree. Is there a way to set a renderer explicitly and will it work without going through the visual tree? Maybe there is an easy way to generate native controls from the ContentView and render them? What are my options here?


SSL Pinning Fails on IOS

$
0
0

I am trying to put ssl pinning on my app.

I followed this tutorial (certificate-pinning-in-xamarin-forms) on how to do it and its working fine on Android, on an iphone 5 device and the iphone emulator (running an iPhone10)

But when I test it on a real device like an iPhone 10 the certificate validation fails

Can anyone help me understand why on the iPhone emulator it runs fine but on a real iPhone 10 device it fails

Problem with ImageButton when changing the Source-Image

$
0
0

Hi,

I'm using the new ImageButton to implement a ToggleButton which switches between a "Locked" and "Unlocked" state.
The "Source"-Property is bound to a bool-Property in the ViewModel and using a ValueConverter to set the name of the according image:

            <ImageButton                    
                Command="{Binding ToggleLockStateCommand}"
                BackgroundColor="Transparent"
                Source="{Binding Locked, Converter={StaticResource cnvLockStateToImage}}">

Changing the images works as expected but after changing the image is not correctly sized, it randomly switches between "very small" and the original size.

I already verified that the ImageButton doesn't change its size when the Source is changed (which is expected as the two images are of the same size).

Anybody has an idea how to fix this (or maybe it's a bug?) My target-platform is Android.

-Michael

ImageSource for button appearing way larger than should be

$
0
0

I am trying to use an image to replace a button to make for better looking UI. I am having a problem with size, it's weird because a couple builds ago it appeared nice and small. My PLUS and DELETE button are both 24x24 and yet they appear larger than that. In the photo I will show my tabbar icons which are 32x32, and yet they are smaller than my other images of smalle size? Can someone please help me? Thanks.

Code

<Button ImageSource="delete.png" BackgroundColor="Transparent"/>
These images are in my drawable folder, I do not have bigger sizes in my drawable-xx.. folders.

Is it possible to cancel an async loop task using a button from another Xaml/cs file?

$
0
0

I have a footer with a button and I'd like to use this button to change page and cancel an async loop task from the content page. When I click on the button, the page changes, but the task continues. And when I go back to the page, the same task starting running again, but it's mean that the task are running twice: the one that haven't been canceled e the new one. It should be only the new one. (I'm using Console.WriteLine to check the task).

I've tried to use the same CancellationToken that I'm using on the content page, but as the button isn't in the same layout, I couldn't figure out how to use it. Any ideas? How can I use the footer button to cancel this task?
Sorry, I'm very new to programming. And sorry about my poor English.

Thanks.

Xamarin.Forms 4.3 pre-release UWP and Shell

$
0
0

I saw that UWP support has tentatively been added to a pre-release version of Forms and thought that I'd give it a try.
I'm having trouble adding a UWP project to a blank template Xamarin.Forms Shell project is there a trick here or should I take a standard Forms template project that includes UWP and try to shoehorn Shell into it?

Viewing all 91519 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>