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

Getting current location in Xamarin.Forms for Android

$
0
0

Hi

What I want to do is quite simple; provide a button that when the user clicks, connects to the Location service and retrieve the Longitude and Latitude of the current location. I've spent hours trying to achieve this using the sample code for Location Service, but it does not work. I don't have any errors, but the OnLocationChanged() does not get fired at all. I am not trying to track location every time it changes, all I want to do is pickup the current location when needed - very simple requirement. Can anyone help please?

Regards

Terence


Circle button in Xamarin.Forms. Super easy way

$
0
0

Guys, there is super easy way to create Circle/Round buttons in XF.
What you need to do is to use BorderRadius, WidthRequest and HeightRequest (you must use all these properties)
Make in mind simple formula:
WidthRequest = BorderRadius * 2
HeightRequest = BorderRadius * 2

or another way:
BorderRadius = WidthRequest / 2
BorderRadius = HeightRequest / 2

So finally, if your WidthRequest and HeightRequest both are equals 40, then your BorderRadius will be 20.
See the attached screens for this simple and nice hack :)

simple text:

font awesome:

Custom view bindable property gives error No Property, Bindable property or event found

$
0
0

I created a custom xamarin view call DetailsCell, the point of it is to reduce repetitive code across the project. In my custom view I created a bindable property as seen below.

        public static readonly BindableProperty CellDetailsTextProperty = BindableProperty.Create(
            nameof(DetailsText),
            typeof(string),
            typeof(DetailsCell),
            string.Empty,
            BindingMode.TwoWay,
            propertyChanged: OnDataChanged);


        public string DetailsText
        {
            get
            {
                return (string)GetValue(CellDetailsTextProperty);
            }

            set
            {
                SetValue(CellDetailsTextProperty, value);
            }
        }

Setting this in xaml with just a string works fine (i.e. <Cells:DetailsCell DetailsText="test"/>), however I get the error: > No property, bindable property, or event found for 'DetailsText' when I try to do the following <Cells:DetailsCell DetailsText="{Binding FromDetailstext}"/> this FromDetailstext comes from the viewmodel of my project. When I do put a normal label and bind the text of the label with "{Binding FromDetailstext}" it works fine. So I have really no idea why this doesn't work any help would be really appreciated

Good plugin/renderer for Round Button

$
0
0

Hi people,

I have been trying to create a custom renderer for a round button. On IOS its working great, on Android however, it works fine on some resolutions and not so much on others.

This is what I have:

public class RoundedButtonRenderer : ButtonRenderer
    {
        private GradientDrawable _normal, _pressed;

        protected override void OnElementChanged(ElementChangedEventArgs<Xamarin.Forms.Button> e)
        {
            base.OnElementChanged(e);

            if (Control != null)
            {
                var button = (RoundedButton)e.NewElement;

                button.SizeChanged += (s, args) =>
                {
                    var radius = (float)Math.Min(button.Width, button.Height);

                    // Create a drawable for the button's normal state
                    _normal = new Android.Graphics.Drawables.GradientDrawable();

                    if (button.BackgroundColor.R == -1.0 && button.BackgroundColor.G == -1.0 && button.BackgroundColor.B == -1.0)
                        _normal.SetColor(Android.Graphics.Color.ParseColor("#ff2c2e2f"));
                    else
                        _normal.SetColor(button.BackgroundColor.ToAndroid());

                    _normal.SetCornerRadius(radius);

                    // Create a drawable for the button's pressed state
                    _pressed = new Android.Graphics.Drawables.GradientDrawable();
                    var highlight = Context.ObtainStyledAttributes(new int[] { Android.Resource.Attribute.ColorActivatedHighlight }).GetColor(0, Android.Graphics.Color.Gray);
                    _pressed.SetColor(highlight);
                    _pressed.SetCornerRadius(radius);

                    // Add the drawables to a state list and assign the state list to the button
                    var sld = new StateListDrawable();
                    sld.AddState(new int[] { Android.Resource.Attribute.StatePressed }, _pressed);
                    sld.AddState(new int[] { }, _normal);
                    Control.SetBackgroundDrawable(sld);
                };
            }
        }
    }

Any help please?

Thanks
Shaun

How to be responsive to user accessibility settings?

$
0
0

I have been tasked with making our app adjust to a user's accessibility settings. Specifically to Extra Large font size.
When I set my phone to use Extra Large fonts, it seems to apply them OK across the board. However, some components look fine whereas some (Labels within a Grid) look all squished together.
1) How can I tell what size of fonts the device is set to?
2) Is there a recommended way to adjust the height of rows in a Grid to fit the font size that the device is set to?
It looks like the android device can change the font size and I would need to change the component height - and probably allow it to wrap and extend.
Thanks!

Binding a Custom Bindable Property to a Property in the view model. Custom ListView

$
0
0

I have this issue, i create a custom list view and create a bindable property call "claveSeleccionadaProperty" an the property "ClaveSeleccionada"
then, i implement this "CustomList" in my xaml file and bind the property that i created previously to my view model as show in the next images

this does not work, i try to recompile the solution and get the next error

when i set the value directly in the xaml, e.g, ClaveSeleccionada="50", this works.

Thanks for your help

Google Play services -Which Xamarin Platform best for integration?

$
0
0

I am a novice programmer and would like to incorporate Google play leader board component into my card game. Where did you start with Xamarin, that is, what platform did you use to integrate the Google Play Services, i.e. Xamarin Forms, Xamarin.Androied, etc?

I am using a Xamarin Forms Portable Class Library with Android and Windows UWP projects. Will this type of platform integrate with Google Play, or do you have to start with a straight Xamarin.Android empty project?

Any advice greatly appreciated!
Thanks - Ron

how to align images ?

$
0
0

Hello guys I have two images in my xaml but these image are not aligned
I want to align my images like this

But I have my images like this

Could Anyone can explain me how can I do this?
My xaml code is this:

    <StackLayout VerticalOptions="Center">

        <StackLayout Orientation="Horizontal" VerticalOptions="End">
            <Image Source="tamalito.png" Aspect="AspectFit" ></Image>
            <Image Source="tamalito.png"  ></Image>
        </StackLayout>

        </StackLayout>

Action Bar - Xamarin Forms

$
0
0

I'm having problems when the virtual keyboard goes up. When I click on the text entry that is in the middle of the screen, the virtual keyboard goes up and the Action Bar. I do not want that to happen, I would like Action Bar to remain intact.

Image of the problem:

Like I wanted it to stay when you clicked on the text entry:

Xamarin.Forms 2.3.4.247

$
0
0

We've published service release 2.3.4.231 to address some priority issues based on your feedback. Thank you!

Important notes

  • Behavior Change (iOS): ViewDidDisappear may not be reliably called in custom renderers. Please be sure to override Dispose to do any object cleanup that you may be doing in ViewDidDisappear to prevent any possible memory leaks in your custom renderers. (53351)
  • Behavior Change (UWP): Desktop is now a supported Idiom, so your UWP apps will return this value on desktop contexts. Please be aware that Phone will still be returned in continuum scenarios.
  • Behavior Change: Merged ResourceDictionaries will now return a Count that is consistent with the content in the enumeration instead of the total Count of Resources.
  • Breaking Change: Attached Properties are now compiled when XamlC is enabled! If you have XamlC enabled, you must implement a public getter/setter for all attached properties to prevent a compile time error.

2.3.4.247-sr2

  • Fix XAMLC build errors in mono 5.0
  • Fix 55365 – ~VisualElement crashes with System.Runtime.InteropServices.COMException

2.3.4.231-sr1

  • [2.3.4] [Android] OnResume assumed that _application had been set (PR)
  • [Xaml] [2.3.4] Do not emit implict_op if from/to are same type (PR)
  • [C] [2.3.4] Lookup in ResourceDictionary also performans a lookup in merged ResourceDictionary (PR)
  • 54334 - "Styles will override properties on UI-Elements when changing resource dictionaries" (PR)

2.3.4.224

For highlights check out the blog announcement and for all the details review the full release notes.

If you have a bug to report, drop us a detailed report here so we can investigate.

Help page

$
0
0

Hi,
I'm really new in this world, i'm doing an app and i want to put in the initial page like a help tutorial, i don't know if it's posible. I want to do it like in some pages when you enter there appears and arrow with like a bubble giving you information about the element, then the arrow change the element making around to diferents elements in the page.
Thanks

Using {Binding .} with value converters

$
0
0

Hi,
I am writing an application using a ListView:

<ListView ItemsSource="{Binding Places}">
        <ListView.ItemTemplate>
          <DataTemplate>
            <ViewCell>
              <Grid>
                <Grid.RowDefinitions>
                  <RowDefinition Height="Auto"/>
                  <RowDefinition Height="Auto"/>
                </Grid.RowDefinitions>
                <Grid.ColumnDefinitions>
                  <ColumnDefinition Width="*"/>
                  <ColumnDefinition Width="Auto"/>
                </Grid.ColumnDefinitions>

                <Label TextColor="White" Text="{Binding Name}" Grid.ColumnSpan="2" FontSize="20" />

                <Label TextColor="White" Text="{Binding Path=. , Converter={StaticResource todayConverter}}" Grid.Row="1" />
                <Label TextColor="White" Text="{Binding Path=. , Converter={StaticResource distanceConverter}}" Grid.Row="1" XAlign="End" Grid.Column="1"/>
              </Grid>
            </ViewCell>
          </DataTemplate>
        </ListView.ItemTemplate>
      </ListView>

I need to pass the whole BindingContext object to my converters but in the converters code is value object set to null:

    class DistanceConverter : IValueConverter
        {
            public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
            {
                //value is set to null
                if (value == null) Debug.WriteLine("value is null");

                PizzaPlace i = value as PizzaPlace;

                if (i.DistanceTo < 500)
                {
                    return String.Format("{0} (cca {1:0} m)", i.City, i.DistanceTo);
                }
                return String.Format("{0} (cca {1:0.0} km)", i.City, i.DistanceTo / 1000);
            }

            public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
            {
                throw new NotImplementedException();
            }
        }

How can I pass whole BindingContext objects to value converters?

ListView rendering after reappearing after Detail Page PopAsync

$
0
0

Hi - Newb to C# / Xamarin / Forums (There are things I am expert at)

I have a Content page (Master) with a ListView (itemsource is observablecollection of Objects) that opens a Content page (Detail) to edit Object properties.

Once the save is made (back to SQLite) - Detail VM sends a messagecenter message with the updated Object. Master Page VM Subscribes and replaces the original Object in the observablecollection with the Updated Object. Detail Page PopAsync's after the save.

Now Master Page reappears. The bindingcontext is updated as expected, but the listview does not render the updated Object. It is there, and can be selected to open the Details page again, but Text & Detail (set through binding to VM) are blank.

I know I could requery SQLite on reappearing - but I am trying to keep the View (MVVM) light. I am completing the Object swap through finding the index, then overwriting the Object in the observablecollection. I have also tried removing the object and adding the new object. Similar result. The only thing that works is a straight up removal of an Object in the collection - they disappear from the ListView as expected - using the same messaging scheme to trigger the collection update.

My preference would be to send Details Page a reference to the Object that is still in Master page, and change properties through the reference. It seems I am sending an object -editing it, and returning an object.

Some Code:

Details Page VIEWModel
public async void SavePlant()
{
await App.Database.SavePlantAsync(Plant);
MessagingCenter.Send(this.Plant, "PlantUpdated");
await App.Current.MainPage.Navigation.PopAsync();
}

Master Page VIEWModel in CTOR

        MessagingCenter.Subscribe<PlantModel>(this, "PlantUpdated", (sender) =>
        {
            //Update the Plant in the list if it was edited elsewhere
            PlantModel p = sender;
            var plantToUpdate = Plants.SingleOrDefault(r => r.PlantID == p.PlantID);
            if (plantToUpdate != null)
            {
                var index = Plants.IndexOf(plantToUpdate);
                Plants[index] = p;
                OnPropertyChanged("Plants");
            }
        });

Unrelated - but this is Master Page View

    protected override void OnAppearing()
    {
        base.OnAppearing();

        PlantSizeListViewModel vm = (PlantSizeListViewModel)BindingContext;
        if (vm.Plants.Count == 0) { Navigation.PopAsync(); }

        if (PlantLV != null)
        {
            PlantLV.ClearValue(ListView.SelectedItemProperty);
        }


    }

(XAML Previewer for Xamarin.Forms) not show in visual studio

$
0
0

HI,

I have visual studio 2015 with xamarin, I have updated to latest alpha version

But when I look at xaml files, I don't see the preview option, how I can enable it? here is how my screen look like (attached)

Thanks

MVVM Bindings

$
0
0

Hi all, I would like to ask why does my basic mvvm bindings doesn't work, see the code below, did I missed something?
//Login.xaml

<local:ButtonLoginCustom Command="{Binding LoginCommand}" Text="Login">
</local:ButtonLoginCustom>`

//Login.xaml.cs

public LoginView()
{
    InitializeComponent();
    BindingContext = new LoginViewModel();
}

//LoginViewModel

public class LoginViewModel : BaseViewModel
{
    public ICommand LoginCommand { get; set; }
    public ICommand LoginCommandExecute =>
    LoginCommand ?? (LoginCommand = new Command(async () => await ExecuteLoginCommand(),
        () => !IsBusy));
}

Thanks for thy inputs!


Add Delay And Cancelation To A Command

$
0
0

I have a search bar in my Xamarin.Forms app. I am trying to set it up so that when the user types the search bar waits for a period of time before sending the search so it does not hit the server on every character. It looks like I need to setup a cancelation token on the actual search function, but it's a command, so i'm not sure how that is supposed to work and even when I tried it as a regular function it didn't work. Does anyone know the proper way to handle this?

Here is my code:

View Model Code Behind:

async void OnTextChanged(object sender, TextChangedEventArgs e)
{
    SearchBar searchBar = sender as SearchBar;
    await ViewModel.SearchThings ("q[name_cont]=" + searchBar.Text);
}

View Model:

private Command _SearchThingsCommand;
public Command SearchThingsCommand { get { return _SearchThingsCommand ?? (_SearchThingsCommand = new Command (async () => await SearchThings())); } }

public async Task SearchThings(string query = "")
{
    if (IsBusy) return;

    IsBusy = true;
    SearchThingsCommand.ChangeCanExecute();

    SearchQuery = query;
    var sv = new ThingService();
    Response response = await sv.GetThingsAsync (1, PerPage, Query);
    TotalPages = response.total_pages;
    Page = response.page;

    Things.Clear ();

    foreach(Thing thing in response.things) {
        Things.Add (thing);
    }

    IsBusy = false;
    SearchThingsCommand.ChangeCanExecute();
}

How to set selectedindex to zero in xaml after itemssource binding from viewmodel to picker?

$
0
0

I would like to set a default value in the Picker. So far I know the "Title" is automatically used but I would like to show one of the options, the Picker shows, e.g. the first one.
I would like to have a xaml solution.
Is there a way to specify the default value in a Picker?

I used this

if I set picOne.SelectedIndex=0;
it is working, but I want to make it work in xaml.

JSON response parsing in Xamarin froms

$
0
0

Hi, I am using Newtonsoft.Json to parse my response coming from API call, title now I found simple kind of json response and able to parse very easily now I have some structure like this

 "data": {
        "error_warning": "",
        "methods": {
            "code1": {
                "code": "code1",
                "title": "Title code1",
                "terms": "",
                "sort_order": "5"
            },
     "code2": {
                "code": "code2",
                "title": "Title code2",
                "terms": "",
                "sort_order": "7"
            }
        },
        "code": "",
        "comment": "",
        "agree": ""
    }

How can I parse these kind of response using model

My previous models are like this

Response format :

    {
        "success": true,
        "data": [
            {
                "category_id": "20",
                "parent_id": "0",
                "name": “Test”,
                "image": "",
                "original_image": "",
                "filters": {
                    "filter_groups": []
                },
                "categories": null
            },
            {
                "category_id": "18",
                "parent_id": "0",
                "name": “test1”,
                "image": "",
                "original_image": "",
                "filters": {
                    "filter_groups": []
                },
                "categories": null
            }
        ]
    }

My model :
public class CategoryResponse
{

    [JsonProperty("success")]
    public string success { get; set; }

    [JsonProperty("data")]
    public List<Category> data { get; set; }

}

public class Category
{

    [JsonProperty("id")]
    public string id { get; set; }

    [JsonProperty("category_id")]
    public string category_id { get; set; }



    [JsonProperty("parent_id")]
    public string parent_id { get; set; }

    [JsonProperty("name")]
    public string name { get; set; }

    [JsonProperty("image")]
    public string image { get; set; }

    [JsonProperty("original_image")]
    public string original_image { get; set; }

    [JsonProperty("categories")]
    public string categories { get; set; }

}

I am able to parse the response like this

            CategoryResponse resp = JsonConvert.DeserializeObject<CategoryResponse>(content);

How to count the time of a running app till app does not close using stopwatch?

$
0
0

i want to count the time of app to its running state to close state..

Xamarin Live Player with Visual Studio 2017 Preview not working

$
0
0

I cannot get to see the Xamarin Live Player with Visual Studio 2017 Preview even after doing everything that is stated in various articles online.
Just wondering if someone could help with what I should be doing to get it working.


I have followed the article below and it does not seem to get me in the right direction. Appreciate your time and help here.

regards,
Sachin

Viewing all 89864 articles
Browse latest View live


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