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

Printing a form

$
0
0

I've been trying for hours to send a form to a printing service for both Android and iOS, something I have absolutely no experience with. I've seen https://forums.xamarin.com/discussion/42417/printing-on-ipad-from-webview which, I thought, sent me on the right path but this prints a WebView control. In my case, I want to print a ContentPage.

As an alternative, I thought of creating a HtmlWebViewSource that would generate the equivalent view of the information I want to print, but again, it doesn't work. My main issue is to go from Xamarin.Forms.WebView to (lets say) Android.Webkit.WebView to access the CreatePrintDocumentAdapter()

In my form, I have:

private void OnPrint()
{
  var WebViewSource = new HtmlWebViewSource()
  {
    Html =
    "<html>" +
    "<body>" +
    "Hello world" +
    "</body>" +
    "</html>"
  };

  var WebView = new WebView() { Source = WebViewSource };
  DependencyService.Get<IPrintService>().Print(WebView);
}

IPrintService is

public interface IPrintService
{
  void Print(WebView webView);
}

and my DependencyService is

[assembly: Dependency(typeof(PrintService))]
namespace Whatever.ApplicationLayer.Droid
{
  public class PrintService : IPrintService
  {
    public void Print(WebView webView)
    {
      var PrintManager = (PrintManager)Forms.Context.GetSystemService(Context.PrintService);
      var AndroidWebView = (Android.Webkit.WebView)webView.On<Xamarin.Forms.PlatformConfiguration.Android>();
      var JobName = "Test";
      PrintManager.Print(JobName, AndroidWebView.CreatePrintDocumentAdapter(JobName), null);
    }
  }
}

When it's time to cast webView, it dies ("System.InvalidCastException: Specified cast is not valid.") What am I doing wrong? What am I missing?


Printing on iPad from WebView

$
0
0

Hello guys,

I want to print a webview with the default printer functionalities which are available on both Android and iOS. I have a DependencyService with a Print method, which calls the platform specific code to access the printing functionalities. The problem is that it is not working on iPad, but it works on Android and iPhones.

The code for iOS is the following:

UIWebView platformWebView = (UIWebView)webView.PlatformControl;

UIPrintInteractionController printer = UIPrintInteractionController.SharedPrintController;

printer.ShowsPageRange = true;

printer.PrintInfo = UIPrintInfo.PrintInfo;
printer.PrintInfo.OutputType = UIPrintInfoOutputType.General;
printer.PrintInfo.JobName = name;

printer.PrintPageRenderer = new UIPrintPageRenderer()
{
    HeaderHeight = 40,
    FooterHeight = 40
};
printer.PrintPageRenderer.AddPrintFormatter(platformWebView.ViewPrintFormatter, 0);

printer.Present(true, (handler, completed, err) =>
{
});

I now that the printer.Present function is primary made for iPhones (http://iosapi.xamarin.com/?link=M:UIKit.UIPrintInteractionController.Present) but it should work when you use True als the first parameter (that's also conform the documentation, not in the doc at the link, but visible when you press F12 on the method in Visual Studio). The problem is that nothing is happening on the iPad when I call this method. No error, nothing.
I am aware of the method printer.PresentFromRectInView, but I don't know what I need to pass as the first two parameters (http://iosapi.xamarin.com/index.aspx?link=M:UIKit.UIPrintInteractionController.PresentFromRectInView).

Does anyone have a working printing solution for iPad?

Thanks in advance.

Regards,
Gerco

CarouselView is throwing dividebyzeroezception when i run the android version.

$
0
0

Hi, am developing a xamarin.Forms application and am using carousel view. it is working fine in iOS version but when i run the android version it is throwing dividebyzero exception. When i comment the CarouselView code in xaml it is not throwing any exception, it is running fine in android as well.Am using Xamarin.Forms.CarouselView nuget package version 2.3.0 pre-2. Can someone please help me out to solve this issue.
below is the code am using it in xaml


                        <BoxView Style="{DynamicResource BoxViewDefaultStyle}" />
                        <AbsoluteLayout 
                HorizontalOptions="Fill"
                VerticalOptions="Fill">
                        <StackLayout Padding="15,10,15,5" Spacing="3" 
                               AbsoluteLayout.LayoutBounds="0,0,1,1"
                 AbsoluteLayout.LayoutFlags="All" 
                 BackgroundColor="{DynamicResource OverlayBackgroundColor}" Orientation="Vertical">
                                                   <Image Source="Ico.png" WidthRequest="35" HeightRequest="35" HorizontalOptions="Center" />

                               <cv:CarouselView Position="{Binding StartPosition, Mode=TwoWay}" ItemsSource="{Binding Data}" HeightRequest="44">
                                    <cv:CarouselView.ItemTemplate>
                                        <DataTemplate>

                                                <Label TextColor="{DynamicResource LightTextColor}" LineBreakMode="WordWrap" FontSize="Micro" VerticalOptions="CenterAndExpand" 
                                                    Text="{Binding Text}" />

                                        </DataTemplate>
                                    </cv:CarouselView.ItemTemplate>
                                </cv:CarouselView>

                            <controls:CarouselIndicators HorizontalOptions="CenterAndExpand" IndicatorHeight="8" IndicatorWidth="8" UnselectedIndicator="IcoCarouselIndicatorUnselectedLightGray.png" SelectedIndicator="IcoCarouselIndicatorSelectedLightGray.png" 
                                                     Position="{Binding StartPosition, Mode=TwoWay}" ItemsSource="{Binding Data}" />
                        </StackLayout>
                             </AbsoluteLayout>
                        <BoxView Style="{DynamicResource BoxViewDefaultStyle}" />



                </StackLayout>

Thanks in advance.

Working OSD joystick on Xamarin forms for Android and iOS

$
0
0

I am trying to create a app that controlls something with a onscreen joystick.
I tried getting the two values by using two sliders, but it didn't work.
There is a library for xamarin, but it is outdated(at least Visual Studio tells me that)
Does anyone have any Idea for this application or a working library.

Pull down refresh indicator not stopping after complete loading

$
0
0

Here is my sample xaml

<ListView ItemsSource="{Binding EmployeeList}" HasUnevenRows="True" 
                          IsPullToRefreshEnabled="True" RefreshCommand="{Binding RefreshCommand}" IsRefreshing="{Binding IsBusy}">
                    <ListView.ItemTemplate>
                        <DataTemplate>
                            <ViewCell>
                                <StackLayout>
                                    <Label Text="{Binding Name}" TextColor="Black"/>
                                    <Label Text="{Binding Department}" TextColor="Black"/>
                                </StackLayout>
                            </ViewCell>
                        </DataTemplate>
                    </ListView.ItemTemplate>
                </ListView>
            </StackLayout>
            <Image Source="{Binding GetSource}"/>

i want that when a user pull down on list view then it will load a image from URI(just playing around)

here is my view model

    public class MainViewModel : INotifyPropertyChanged
    {
        private List<Employee> _employeeList { get; set; }

        private string _source { get; set; }

        public string GetSource { get { return _source; } set { _source = value; OnPropertyChanged(); } }


        Command _refreshCommand;
        public Command RefreshCommand
        {
            get
            {
                return _refreshCommand;
            }
        }

        public List<Employee> EmployeeList
        {
            get { return _employeeList; }
            set { _employeeList = value;
                OnPropertyChanged();
            }
        }

        // class constractor
        public MainViewModel()
        {
            var employeeServices = new EmployeeServices();
            EmployeeList = employeeServices.GetEmployees();
            _refreshCommand = new Command(ShowImage);
        }

        private void ShowImage()
        {
            var imagesou = "https://www.hindustantimes.com/rf/image_size_640x362/HT/p2/2016/04/08/Pictures/_e76dfb4e-fd62-11e5-bced-6695953481e2.jpg";
            GetSource = imagesou;
        }

        #region PropertyChange
        public event PropertyChangedEventHandler PropertyChanged;

        protected virtual void OnPropertyChanged([CallerMemberName] string propertyName=null)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }
        #endregion
}

Problem is that when I pull down for refreshing,then it works fine,but after complete image loading the refresh indicator is not stopping,so how to do this?

implement chronometer on local notification on Android [Xamarin.Forms]

$
0
0

I want to implement a chronometer in my xamarin.forms app, in an specific way on android, how can I create a notification that has a chronometer in it? as the following image shows:

How to display custom layout multiple times in Xamarin Forms

$
0
0

I have a Custom Rating bar layout in Xamarin, I want to display it multiple times in my form but it is displaying only once even though i have declared it multiple times but is showing only one time & last layout.

<?xml version="1.0" encoding="UTF-8"?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             Title="Reviews"
             xmlns:customcontrol="clr-namespace:MyApp.NestedLayouts"
             x:Class="MyApp.Pages.Reviews">
    <ContentPage.Content>
        <Grid>
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="110"/>
                <ColumnDefinition Width="*"/>
            </Grid.ColumnDefinitions>
            <Grid.RowDefinitions>
                <RowDefinition Height="100"/>
                <RowDefinition Height="Auto"/>
            </Grid.RowDefinitions>
            <Label Text="4.5" FontSize="30" VerticalOptions="CenterAndExpand" HorizontalOptions="CenterAndExpand"
                   FontAttributes="Bold"/>
            <StackLayout Grid.Column="1">
                <customcontrol:RattingBar x:Name="layout1" ImageWidth="20" ImageHeight="20" RequiredStarValue="5"
                                          SelectedStarValue="5" FillStarImage="StarF.png" EmptyStarImage="star.png" />
                <Label Text="2 Reviews"/>
            </StackLayout>

            <Grid Grid.ColumnSpan="2" Grid.Row="1">
                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="110"/>
                    <ColumnDefinition Width="*"/>
                    <ColumnDefinition Width="40"/>
                    </Grid.ColumnDefinitions>

                <Grid.RowDefinitions>
                    <RowDefinition Height="*"/>
                    <RowDefinition Height="*"/>
                    <RowDefinition Height="*"/>
                    <RowDefinition Height="*"/>
                    <RowDefinition Height="*"/>
                </Grid.RowDefinitions>
                <!-- Row 0 -->
                <customcontrol:RattingBar ImageWidth="18" ImageHeight="18" RequiredStarValue="5" x:Name="layout2"
                                          SelectedStarValue="5" FillStarImage="StarF.png" EmptyStarImage="star.png" />
                <BoxView Grid.Column="1" HeightRequest="1" VerticalOptions="CenterAndExpand"
                         BackgroundColor="{DynamicResource gray}"/>
                <Label Grid.Column="2" Text="1" HorizontalOptions="CenterAndExpand"/>

                <!-- Row 1 -->
                <customcontrol:RattingBar ImageWidth="18" ImageHeight="18" RequiredStarValue="4" Grid.Row="1" x:Name="layout3"
                                          SelectedStarValue="4" FillStarImage="StarF.png" EmptyStarImage="star.png" />
                <BoxView Grid.Column="1" HeightRequest="1" VerticalOptions="CenterAndExpand" Grid.Row="1"
                         BackgroundColor="{DynamicResource gray}"/>
                <Label Grid.Column="2" Text="1" HorizontalOptions="CenterAndExpand" Grid.Row="1"/>

            </Grid>
        </Grid>
    </ContentPage.Content>
</ContentPage>

This is the layout Which i want to use multiple times but can't achieve (I have added my Views in backend).

<?xml version="1.0" encoding="UTF-8"?>
<ContentView xmlns="http://xamarin.com/schemas/2014/forms" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="MyApp.NestedLayouts.RattingBar">
        <StackLayout Orientation="Horizontal"/>
</ContentView>

TextToSpeech.SpeakAsync from Xamarin.Essentials doesn't produce any sound

$
0
0

Hi,
I try the TextToSpeech.SpeakAsync feature, but it I gets no sound and no error is shown.
In addition, the row after the await is never reached.

private async void Button1_OnClicked(object sender, EventArgs e)
{
await TextToSpeech.SpeakAsync("Hi there");
int x = 9; //this row is never reached
}

P.S I use Android 6.0.1 The media and sounds level are on maximum.


Set Background Image For Tabbed Page

$
0
0

Hi, I want to set background Image for tabbed page in above it , look like this :

Using AudioTrack to play consistent stream of PCm data

$
0
0

I have an application that gets consistent stream of PCm data, in a while loop. The loop works untill the stream has data. I then read the incomming stream into a byte[] and then write it to AudioTrack. The problem is that it plays ok for a couple of seconds, but then you can hear a lot of noise and sometimes audio again, but it works poorly. I tried to increase the buffer size of AudioTrack constructor, but no luck. The commented part was my try to have the data saving into a list in a sepperate thread, and then use that data, remove it and so on, on a different thread also. Like a self made buffer of sort. That works better, but it still has some interuptions, but less of them, and you can hear more audio.

For the first one you can hear like 1-2 seconds of music, than about 5s of noise, then just noise or sometimes audio, but for second one, you can hear a lot of music, then sometimes noise, but it stops playing comleatly.

This is my code:

public void Read()
    {
        System.Threading.Tasks.Task.Run(() =>
        {
            int _bufferSize;
            //List<byte[]> Queued = new List<byte[]>();
            AudioTrack _output;

            _bufferSize = AudioTrack.GetMinBufferSize(44100, ChannelOut.Stereo, Android.Media.Encoding.Pcm16bit);
            _output = new AudioTrack(Android.Media.Stream.Music, 44100, ChannelOut.Stereo, Android.Media.Encoding.Pcm16bit,
                _bufferSize, AudioTrackMode.Stream);
            _output.Play();

            byte[] myReadBuffer = new byte[8000];
            //bool bufferCheck = true;

            while (mmInStream.CanRead)
            {
                try
                {
                    mmInStream.Read(myReadBuffer, 0, myReadBuffer.Length);                        
                    //Queued.Add(myReadBuffer);
                    _output.Write(myReadBuffer, 0, myReadBuffer.Length);

                    /*System.Threading.Tasks.Task.Run(() =>
                    {
                        while (true)
                        {
                            try
                            {
                                /*if (Queued.Count != 0)
                                {
                                    if (bufferCheck)
                                    {
                                        Thread.Sleep(100);
                                        bufferCheck = false;
                                    }
                                    var bytes = Queued[0];
                                    Queued.Remove(bytes);
                                    _output.Write(bytes, 0, bytes.Length);
                                }
                                else
                                {
                                    break;
                                }*/
                                if (bufferCheck)
                                {
                                    Thread.Sleep(100);
                                    bufferCheck = false;
                                }
                                var bytes = Queued[0];
                                Queued.Remove(bytes);
                                _output.Write(bytes, 0, bytes.Length);
                            }
                            catch (Exception ex)
                            {
                                System.Diagnostics.Debug.WriteLine("Writing", ex);
                            }
                        }
                    }).ConfigureAwait(false);*/
                }
                catch (System.IO.IOException ex)
                {
                    System.Diagnostics.Debug.WriteLine("Input stream was disconnected", ex);
                }
            }
            _output.Stop();
        }).ConfigureAwait(false);
    }

How to Xamarin.Forms Dependency Injection with dynamic constructor parameter?

$
0
0

Happy new year to everyone!

My question concerns how to use DI in a Xamarin.Forms View to resolve a ViewModel where the ViewModel needs a dynamic (different every time) constructor parameter which parameter needs to be constructed inside the View. If it is feasible, I would like to use ASP NET Core DI. I have read James Montemagno's post about DI, but I dont think it contains the answer to my question.

Here is my code in its current, non-DI form:
We are inside the MovieDetailPage() constructor and the Page's constructor creates its own ViewModel and assigns it to its binding context like this:

    public MovieDetailPage(MovieDetailModel movie)
    {
        ViewModel = new MovieDetailPageViewModel(
            movie,
            ((App)Application.Current).Settings,
            ((App)Application.Current).TmdbApiService,
            ((App)Application.Current).UsersMovieListsService2,
            ((App)Application.Current).MovieDetailModelConfigurator,
            ((App)Application.Current).PersonDetailModelConfigurator,
            ((App)Application.Current).VideoService,
            ((App)Application.Current).WeblinkComposer,
            **new PageService(this)**
            );

        InitializeComponent();
    }

The page extracts the dependencies from the Application by accessing the properties in ((App)Application.Current).. These dependencies have a lifetime equal to the application and do not change. My understanding is, that we could easily resolve them via DI if we register them with Singleton lifetime.

My problem is the object which the Page constructs via new PageService(this) . PageService basically provides means for the ViewModel to access some Xamarin.Forms navigation and DisplayAlert() functions by exposing some of the API of Navigation and Page through an IPageService interface.

For this the PageService object needs to be constructed dynamically with the current pages reference.

What options do I have to use Dependency Injection for resolving the ViewModel from the View's constructor in a way so that I can provide a valid PageService object. For better understanding I have copied some code from IPageService-PageService below.

====================================================================

public interface IPageService
{
    ..
Task DisplayAlert(string title, string message, string cancel);
    ...
    Task OpenWeblink(string url);
}

public class PageService : IPageService
{
    private readonly Page _currentPage;

    public PageService(Page current) => _currentPage = current;
    ...

    public async Task DisplayAlert(string title, string message, string cancel) =>
        await _currentPage.DisplayAlert(title, message, cancel);
    ...

    public async Task OpenWeblink(string url)
    {
        try
        {
            await Browser.OpenAsync(url, BrowserLaunchMode.SystemPreferred);
        }
        catch (Exception ex)
        {
            await _currentPage.DisplayAlert("Error", $"Could not open weblink: {ex.Message}", "Ok");
        }
    }
}

Tiled Background?

$
0
0

For a tiled background in Xamarin for an iOS project I can do:

public override void ViewDidLoad()
{
     base.View.BackgroundColor = UIColor.FromPatternImage(UIImage.FromFile("Graphics/ScannerBackgroundTile.png"));
}

How to I achieve the same cross platform in Xamarin Forms Portable in XAML? Thanks.

quick question xamarin from shell Navigation

$
0
0

i have tow shell one for login and other for the rest of the app how i can navigte after login to the main shell i tried

await Navigation.PushModalAsync(new NavigationPage(new AppShell()));

but it went to shell main page but without Flyout menu

Binding Command for Button inside a ListView and Toggled Action from Switch inside ListView

$
0
0

Hi everyone,

I'm trying to add a command to a button inside a listview in a MVVM architecture, but i'm not being so succeed. Also i'm trying to attach an action to when the switch is toggled, but i have no idea how to do that (and i know that i can put an method inside the SET property in the MODEL, but i want to call an method from the view model). The data from the notification model (Time, Legend, Activated and AlarmStatus) is appearing on the screen and the button outside the listview is working as well... See bellow my code until now:

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="AppTest.Views.NotifyManager">
  <ContentPage.Content>
    <StackLayout Padding="25">
      <Button Text="Add" Command="{Binding AddNotify} />
      <ListView ItemsSource="{Binding Notifications}" HasUnevenRows="True" SelectedItem="{Binding notifSelected}">
        <ListView.ItemTemplate>
          <DataTemplate>
            <ViewCell>
              <ViewCell.View>
                <StackLayout>
                  <Label Text="{Binding Time}" FontSize="20"/>
                  <Label Text="{Binding Legend}" FontSize="15"/>
                  <Switch IsToggled="{Binding Activated}" />
                  <Label Text="{Binding AlarmStatus}" FontSize="15"/>
                  <Button Text="Remove" Command="{Binding ???}"/>
                </StackLayout>
              </ViewCell.View>
            </ViewCell>
          </DataTemplate>
        </ListView.ItemTemplate>
      </ListView>
    </StackLayout>
  </ContentPage.Content>
</ContentPage>

and the view model:

namespace AppTest.ViewModel
{
    class NotifyManagerViewModel
    {
        SaveNotification sn;
        public ObservableCollection<Notification> Notifications { get; set; }
        private NotificationDAO dao;
        public ICommand AddNotify { get; protected set; }
        public INavigation Navigation { get; set; }

        private Notification notifSelected;
        public Notification notifSelected
        {
            get
            {
                return notifSelected;
            }
            set
            {
                if(notifSelected != value)
                {
                    notifSelected = value;
                }
            }
        }

        public NotifyManagerViewModel(NotificationDAO notDao)
        {
            dao = notDao;
            Notifications = dao.Notifications;

            AddNotify = new Command(() => 
            {
                sn = new SaveNotification(dao);
                Navigation.PushAsync(sn);
            });
        }

    }
}

Thanks :)

Allow the Editor control to grow as content lines are added

$
0
0

I have been modifying the Todo app that uses Forms and replaced the note Entry class with the Editor class, so the todo can hold multiline notes. However the editor does not expand as new lines are entered. I have a Forms Editor Control nested inside a stack layout / scroll view - how do I allow the editor to grow each time the user enters another line of data? I had some success by count the '\n' characters in the text each time it changes and making a HeightRequest to the Editor, but I don't know how to calculate the exact extra height to add for each row in a reliable way. This process also feels clunky too. Can the editor control not be told to simply grow as new content is added by the user?


ScrollView NullReference

$
0
0

hi
Why do I get this error

The project is okay if we don't use it

load TabbedPage in ContentPage

$
0
0


Slideshow page
Views Page

Shared Page

How to create a camera app in xamarin app

$
0
0

Suggest best ways to create a camera app, and best plugins available for using cama in xamarin forms cross platform app

How to bind an image to a ListView template?

$
0
0

Hello, I'm trying to load icons to the menu page and want to use a template which will be bound to a collection of View Models. I have the text part working, but for some reason the icon doesn't.
I'm very sorry if the post is too long, I just don't know how else to show you the problem. Thanks in advance!

XAML:

<StackLayout VerticalOptions="FillAndExpand">
        <ListView x:Name="ListViewMenu" HasUnevenRows="True" >                
            <ListView.ItemTemplate>
                <DataTemplate>
                    <ViewCell>
                        <Grid Padding="10">
                            <Grid.ColumnDefinitions>
                                <ColumnDefinition Width="25" />
                                <ColumnDefinition Width="*" />
                            </Grid.ColumnDefinitions>
                            <Image Source="{Binding Icon}" Aspect="AspectFit" />
                            <Label Text="{Binding Title}" FontSize="20" Grid.Column="1" />
                        </Grid>
                    </ViewCell>
                </DataTemplate>
            </ListView.ItemTemplate>
        </ListView>
    </StackLayout>

Code Behind:

public partial class MenuPage : ContentPage
{
    MainPage RootPage { get => Application.Current.MainPage as MainPage; }
    List<HomeMenuItem> menuItems;
    public MenuPage()
    {
        InitializeComponent();

            menuItems = new List<HomeMenuItem>
            {
                // This is where I dictate the images' sources
                new HomeMenuItem {Id = MenuItemType.Home, Title="Home", Icon = new Image { Source = "home_blk.png" } },
                new HomeMenuItem {Id = MenuItemType.Holdings, Title="Holdings", Icon = new Image(){ Source = "show_chart_blk.png" }},
                new HomeMenuItem {Id = MenuItemType.Gain, Title="Gain", Icon = new Image(){ Source = "home_blk.png" } }
            };

            // This is where I set the ListView's source
            ListViewMenu.ItemsSource = menuItems;

            ListViewMenu.SelectedItem = menuItems[0];
            ListViewMenu.ItemSelected += async (sender, e) =>
            {
                if (e.SelectedItem == null) return;

                var id = (int)((HomeMenuItem)e.SelectedItem).Id;
                await RootPage.NavigateFromMenu(id);
            };
    }
}
public enum MenuItemType
{
    Home, Holdings, Gain
}
public class HomeMenuItem
{
    public Image Icon { get; set; }
    public MenuItemType Id { get; set; }
    public string Title { get; set; }
}

How navigate to a Content Page from Rg popup on clicking a button

$
0
0

I have created a popup using rg.plugins.popup. In my popup i have a button so when i click that button want to display a report(ie, form is contentpage)
so its showing error when im using Navigation.PushAsync() .
whil using PopupNavigation.Instance.PushAsync() this also showing error as my form is not a popup .

Please help !.....

Viewing all 91519 articles
Browse latest View live


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