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

What is the ListDictionaryInternal Involved in UpdateMainPage()?

$
0
0

I am encountering an error when assigning a new page to a class parameter. It appears that it has not been initialized and is null. What is it and how is it initialized? The code is in the PCL and has no problems in either Android or UWP.

<p>Object reference not set to an instance of an object</p><p>Data ----------</p><p>System.Collections.ListDictionaryInternal</p><p>HResult ----------</p><p>-2147467261</p><p>Source ----------</p><p>Xamarin.Forms.Platform.iOS</p><p>StackTrace ----------</p><p>  

at Xamarin.Forms.Platform.iOS.FormsApplicationDelegate.UpdateMainPage () [0x0000e] in d:\a\1\s\Xamarin.Forms.Platform.iOS\FormsApplicationDelegate.cs:198 \n at Xamarin.Forms.Platform.iOS.FormsApplicationDelegate.ApplicationOnPropertyChanged (System.Object sender, System.ComponentModel.PropertyChangedEventArgs args) [0x00012] in d:\a\1\s\Xamarin.Forms.Platform.iOS\FormsApplicationDelegate.cs:152 \n at Xamarin.Forms.BindableObject.OnPropertyChanged (System.String propertyName) [0x00000] in d:\a\1\s\Xamarin.Forms.Core\BindableObject.cs:229 \n at Xamarin.Forms.Element.OnPropertyChanged (System.String propertyName) [0x00000] in d:\a\1\s\Xamarin.Forms.Core\Element.cs:353 \n at Xamarin.Forms.Application.set_MainPage (Xamarin.Forms.Page value) [0x0008b] in d:\a\1\s\Xamarin.Forms.Core\Application.cs:91


Two way binding not working as expected

$
0
0

Hi,

I'm a bit confused right now and can't get my head around this.

I have a custom view that has a property IsCollapsed. Based on this property the view shows or hides its content. So far so good.
This property works well when I directly access it, for example like:

MyView.IsCollapsed = true;

will collapse the view.

However the goal of course is to have the property bound to a value in my ViewModel. But for now I didn't manage to have the view model update the IsCollapsed property of the view.

So here is my View Model:

public class ViewModel : INotifyPropertyChanged
{
            public bool Collapsed { get { return _collapsed; } set { _collapsed = value; OnPropertyChanged(); } }
            protected bool _collapsed { get; set; } = true; 

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

And here is the custom View part:

public class ExpandableLayout : StackLayout
{
        public static readonly BindableProperty IsCollapsedProperty = BindableProperty.Create(nameof(IsCollapsed), typeof(bool),        typeof(ExpandableLayout),defaultValue:false, defaultBindingMode:BindingMode.TwoWay);

    public bool IsCollapsed 
    {   get { return (bool)GetValue(IsCollapsedProperty); }
            set
        {
                ExecuteCollapseStateChange();
                SetValue(IsCollapsedProperty, value);
                OnPropertyChanged();
            }
        }
}

And I want to change the models property from a tap on the cell in a list view just like that:

void TestList_ItemTapped(System.Object sender, Xamarin.Forms.ItemTappedEventArgs e)
{
            if (e.Item is ViewModel model)
                model.Collapsed = !model.Collapsed;
}

I can see the ItemTapped being fired and the value in the view model is changing, but the value in the ExpandableLayout is not updated. Any ideas?

Thank you!

Java.Lang.Outofmemory

$
0
0

Java.Lang.OutOfMemoryError: 'Failed to allocate a 2322588 byte allocation with 425320 free bytes and 415KB until OOM'

how can i fix this error?

Is it possible to use socket connection from IPad using Xamarin.Form for deploy the app in the IPad?

$
0
0

Can I use socket connection form IPAD using Xamarin.Form. When I try it throws “Access Denied Exception”.

readonly Socket DiscoverySocket = new Socket(SocketType.Dgram, ProtocolType.Udp) { EnableBroadcast = true };
const int DiscoveryPort = 7002;

------------method-----------
DiscoverySocket.Bind(new IPEndPoint(IPAddress.Any, 0));
foreach (var ni in NetworkInterface.GetAllNetworkInterfaces())
if (ni.OperationalStatus == OperationalStatus.Up && ni.NetworkInterfaceType != NetworkInterfaceType.Loopback)
foreach (var unicastIpAddress in ni.GetIPProperties().UnicastAddresses)
if (unicastIpAddress.Address.AddressFamily == AddressFamily.InterNetwork)
{
var broadcast = unicastIpAddress.Address.GetBroadcastAddress(unicastIpAddress.IPv4Mask);

var ep = (EndPoint)new IPEndPoint(broadcast, DiscoveryPort);

DiscoverySocket.SendTo(Array.Empty(), ep);

This last line throws Access Denied Exception.

Need Element to be above keyboard on Android

$
0
0

Hi! I have a Xamarin forms ContentPage that looks like this :

<StackLayout>
    <SearchBar>
    <StackLayout>
            <ListView>
        <Map (Xamarin.Forms.Maps)>
        <CarouselView Orientation='Horizontal'>

The user should be able to search for a location in the search bar, Google Locations API populates the list view with a few suggestions, the user selects one and the map is updated with Pins and Polylines to present the data. The carousel view is populated with the locations so the user can clearly see the route they are making. This all works fairly well.

My issue is when the user focuses the search bar and the keyboard pops up it hides the carousel view, which is pretty important for the user experience. Ideally, I would like it to sit just above the keyboard when it is present.

I've tried a few things, including:

  • Wrapping everything in a scrollView - doesn't work with the map view
  • Window.SetSoftInputMode(Android.Views.SoftInput.AdjustResize); - doesn't seem to effect anything

This post seems to recommend the best solution, however it's for iOS and I'm not good enough to translate it to Android:
https://forums.xamarin.com/discussion/12715/how-to-get-size-of-the-keyboard

Any help would be greatly appreciated :)

How to get Hamburger Icon in iOS?

$
0
0

I've got the icon, and it shows in the Navigation for Android, but I can't see it for iOS. How do I get the Hamburger Icon in iOS?

It's loaded in my Menu.xaml (Master)

<ContentPage
    xmlns="http://xamarin.com/schemas/2014/forms"
    xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
    x:Class="FutureState.AppCore.Pages.MainMenu"
    Title="Breathing Room" Icon="ic_drawer_light.png">

The icon is located in my iOS/Resources directory as Bundle / Do Not Copy, and it's in there twice... once as ic_drawer_light.png and once as ic_drawer_light@2x.png

Am I missing something?

Adjust Width of Master on MasterDetailPage

$
0
0

I am using the MasterDetailPage for the NavigationDrawer on Android. Implementing the functionality has gone perfectly, however the width is too large and i would like to adjust it.

I have tried to set the WidthRequest for the ListView CellTemplate, ListView, and the Master Property of the MasterDetailPage all to the same value, and i can see that the cells are at the right width but the slide out part is still too big.

public MainPage(Action loginFaliedCallback) { MenuPage menu = new MenuPage { Title = "Menu", WidthRequest = 250 }; menu.Menu.ItemSelected += (s, e) => NavigateTo(e.SelectedItem as MenuItem); Master = menu; Master.WidthRequest = 250; }
Any information would be greatly appreciated. Thanks in advance.

Fill list turns into cast error

$
0
0

Hi, i want to fill a simple list and bind that to a listview. when i start-up the app i do get the error:
System.InvalidCastException: 'Specified cast is not valid.' at:
MainActivity.cs at:
Xamarin.Essentials.Platform.Init(this, savedInstanceState); global::Xamarin.Forms.Forms.Init(this, savedInstanceState); LoadApplication(new App());
Code:

XAML:
<ListView ItemsSource="{Binding items}"> <ListView.ItemTemplate> <DataTemplate> <StackLayout Orientation="Horizontal"> <Label Text="{Binding id}"/> <Label Text="{Binding name}"/> <Label Text="{Binding desc}"/> </StackLayout> </DataTemplate> </ListView.ItemTemplate> </ListView>

XAML.CS

``
public partial class MainPage : ContentPage
{
public List items { get; set; }

    public MainPage()
    {
        InitializeComponent();
        BindingContext = this;
        FillList();
    }

    public void FillList()
    {

        items.Add(new Item { id = 1, name = "test1", desc = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec sit." });
        items.Add(new Item { id = 2, name = "test2", desc = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec sit." });
        items.Add(new Item { id = 3, name = "test3", desc = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec sit." });
        items.Add(new Item { id = 4, name = "test4", desc = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec sit." });
        items.Add(new Item { id = 5, name = "test5", desc = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec sit." });
        items.Add(new Item { id = 6, name = "test6", desc = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec sit." });
        items.Add(new Item { id = 7, name = "test7", desc = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec sit." });
        items.Add(new Item { id = 8, name = "test8", desc = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec sit." });
        items.Add(new Item { id = 9, name = "test9", desc = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec sit." });
        items.Add(new Item { id = 10, name = "test10", desc = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec sit." });

    }
}

``

Item.cs
public class Item { public int id { get; set; } public string name { get; set; } public string desc { get; set; } }

hope someone can tell me whats wrong cuz its really frustrating.


iOS page covers status bar

$
0
0

What should I do to prevent the application cover the status bar area?
It covers the whole window and status icons are visible through top_grid on iPad 2 simulator


<?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="test_cs_mobile_xamarin.main_page">
   <StackLayout>
      <Frame x:Name="top_frame" HasShadow="true" OutlineColor="Green" Padding="5,5,5,5" VerticalOptions = "FillAndExpand">
         <ScrollView  x:Name="top_scroll_view" VerticalOptions = "FillAndExpand">
            <Grid x:Name="top_grid" VerticalOptions = "FillAndExpand">
               <Grid.Children>
               </Grid.Children>
            </Grid>
         </ScrollView>
      </Frame>
      <Frame x:Name="bottom_frame" HasShadow="true" OutlineColor="Green" Padding="5,5,5,5" VerticalOptions = "FillAndExpand">
         <ScrollView x:Name="bottom_scroll_view" VerticalOptions = "FillAndExpand">
            <Label  Text="..." XAlign="Start" YAlign="Start" VerticalOptions="FillAndExpand" HorizontalOptions="FillAndExpand" x:Name="bottom_label" LineBreakMode="WordWrap" />
         </ScrollView>
      </Frame>
      <StackLayout x:Name="bottom_stack_layout" Orientation="Horizontal">
         <Button Text="Add 1" x:Name="button_1"></Button>
         <Button Text="Add 2" x:Name="button_2"></Button>
         <Button Text="http" x:Name="button_3"></Button>
         <Button Text="http 1" x:Name="button_4"></Button>
      </StackLayout>
   </StackLayout>

Error with CollectionView RemainingItemsThreshholdReached Command

$
0
0

I use Prism MVVM in my app. So here is my XAML code

<RefreshView Grid.Row="1"

                 IsRefreshing="{Binding IsRefreshing}"
                 Command="{Binding RefreshCommand}">

        <CollectionView ItemsSource="{Binding Images}"
                        RemainingItemsThreshold="1"
                        RemainingItemsThresholdReachedCommand="{Binding UpdateImagesCommand}">
        <CollectionView.ItemsLayout>
            <GridItemsLayout Orientation="Vertical"
                             Span="3"/>
        </CollectionView.ItemsLayout>
        <CollectionView.ItemTemplate>
            <DataTemplate>
                <Grid Padding="2">
                    <Grid.RowDefinitions>
                        <RowDefinition/>
                    </Grid.RowDefinitions>
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition/>
                    </Grid.ColumnDefinitions>
                <ff:CachedImage 
                    Grid.Row="0"
                    Grid.Column="0"
                    HorizontalOptions="Center"
                    VerticalOptions="Center"
                    Aspect="AspectFill"
                    Source="{Binding Source, Mode=OneWay}">
                    <ff:CachedImage.Transformations>
                            <ffTransformations:CropTransformation />
                        </ff:CachedImage.Transformations>
                </ff:CachedImage>
                </Grid>
            </DataTemplate>
        </CollectionView.ItemTemplate>
    </CollectionView>
    </RefreshView>

As you can see here I have parameter RemainingItemsThreshold with the value "1", and binding anUpdateImagesCommand to the RemainingItemsThresholdReachedCommand

Here is a part of a code in view model of this xaml page

private ObservableCollection _images;
public ObservableCollection Images
{
get { return _images; }
set { SetProperty(ref _images, value); }
}
private DelegateCommand _refreshCommand;
public DelegateCommand RefreshCommand =>
_refreshCommand ?? (_refreshCommand = new DelegateCommand(ExecuteRefreshCommand));

    private DelegateCommand _updateImagesCommand;
    public DelegateCommand UpdateImagesCommand =>
        _updateImagesCommand ?? (_updateImagesCommand = new DelegateCommand(ExecuteUpdateImagesCommand));

void ExecuteUpdateImagesCommand()
{
//Image im = new Image();
//im.Source = "Huayra3.jpg";
//Image im7 = new Image();
//im7.Source = "Huayra1.jpg";

        //Images.Add(im7);
        //Images.Add(im7);
        //Images.Add(im);
        //Images.Add(im);
        //Images.Add(im);
        //Images.Add(im);
    }

void ExecuteRefreshCommand()
{
// refresh posts feed command
IsRefreshing = false;
}

public AccountPageViewModel(INavigationService navigationService, IUserDataService userDataService) :
base(navigationService)
{
_userDataService = userDataService;
CurrentUser = userDataService.CurrentUser;

        if (String.IsNullOrEmpty(this.CurrentUser.ImagePath))
        {
            this.CurrentUser.ImagePath = "user_avatar.jpg";     
        }

        Images = new ObservableCollection<Image>();

        Image im = new Image();
        im.Source = "Huayra3.jpg";
        Images.Add(im);
        Image im1 = new Image();
        im1.Source = "Huayra1.jpg";
        Images.Add(im1);
        Image im2 = new Image();
        im2.Source = "Huayra4.jpg";
        Images.Add(im2);
        Image im3 = new Image();
        im3.Source = "Huayra3.jpg";
        Images.Add(im3);
        Image im4 = new Image();
        im4.Source = "Huayra1.jpg";
        Images.Add(im4);
        Image im5 = new Image();
        im5.Source = "Huayra4.jpg";
        Images.Add(im5);
        Image im6 = new Image();
        im6.Source = "Huayra3.jpg";
        Images.Add(im6);
        Image im7 = new Image();
        im7.Source = "Huayra1.jpg";
        Images.Add(im7);
        Images.Add(im7);

        Images.Add(im7);
        Images.Add(im7);
        Images.Add(im7);
        Images.Add(im7);
        Images.Add(im7);
        Images.Add(im);


        //Images.Add(im);
        //Images.Add(im);

    }

As you can see I in my VIewModel constructor I've written some values and add it to list. I read microsoft documentation about CollectionView and I know that the UpdateImagesCommand will execute only when the RemainingItemsThreshold is reached. But ExecuteUpdateImagesCommand() invokes when I navigate to this page, when I navigating between my pages in my tabbed page randomly. This should not be, but I do not know the reason why this happens. Can smbd help me please?

How can I prevent ListView from flickering (in GTK only) when making any changes?

$
0
0

I have a Xamarin.Forms build which contains a ListView bound to an ObservableCollection. My end goal is to regularly update this ObservableCollection using a MessagingCenter subscription which is triggered by an HTTPRequest elsewhere in the app's code, but this is beside the point. I'm developing the app for use on a Raspberry Pi, and as such the GTK support has been great, but I've noticed that when adding or removing any items within the ObservableCollection, the entire list flickers. This issue only occurs in the GTK build, however. Updates are smooth in Android.

I've seen solutions for Android using things like DoubleBuffer, but since this seems like a pretty complex solution and I was having trouble understanding exactly how to implement it, I wanted to see if anyone was aware of an easier fix that was GTK specific or at least of where I could start looking for issues within the GTK build.

It should be noted that I've tried adding and removing list items from just about everywhere, including locally within the ListPageViewModel (ignoring MessagingCenter). I've included the code for the ViewModel containing the ObservableCollection and the MessagingCenter Subscription as well as the ListPage xaml. Any thoughts would be appreciated.

ListPageViewModel:

using MyApp.Models;
using MyApp.Views;
using System.Collections.ObjectModel;
using Xamarin.Forms;

namespace MyApp.ViewModels
{
    public class ListPageViewModel
    {
        public ObservableCollection<MyItem> MyList { get; private set; } = new ObservableCollection<MyItem>();
        public MyItem SelectedMyItem { get; set; }
        INavigation Navigation;
        ListUpdater listUpdater; //This is a separate class which will be doing all of the comparisons and adding/removing on each new message

        public ListPageViewModel(INavigation MyListNavigation)
        {
            Navigation = MyListNavigation;
            listUpdater = new ListUpdater(MyList); //passing the list by reference into the updater class
            MessagingCenter.Subscribe<object, ObservableCollection<MyItem>>(Application.Current, Constants._listUpdateContract, (sender, argument) =>
            {

                listUpdater.AddToList(); //This method of the ListUpdater class currently only adds a new MyItem to the list
                          //I have also added and removed MyItems locally, inside a loop, without depending on the MessagingCenter      
            });
        }
    }
}

XAML for ListView:

<ContentPage.Content>
        <StackLayout Orientation="Horizontal">
            <ListView x:Name="MyList"
                      HasUnevenRows="True"
                      SeparatorVisibility="Default"
                      VerticalOptions="FillAndExpand"
                      SelectedItem="{Binding SelectedMyItem, Mode=TwoWay}"
                      ItemsSource="{Binding MyItems}"
                      ItemSelected="myList_ItemSelected">

                <ListView.BackgroundColor>
                    <OnPlatform x:TypeArguments="Color">
                        <On Platform="GTK" Value="White" />
                    </OnPlatform>
                </ListView.BackgroundColor>

                <ListView.ItemTemplate>
                    <DataTemplate>
                        <ViewCell>
                            <StackLayout Orientation="Vertical"
                                         VerticalOptions="CenterAndExpand">
                                <Grid HorizontalOptions="Center"
                                      VerticalOptions="FillAndExpand">
                                    <Label Grid.Row="0"
                                           Grid.Column="0"
                                           HorizontalOptions="Center"
                                           Text="{Binding TypeAndId}"
                                           FontSize="Medium"/>
                                </Grid>
                                <Grid HorizontalOptions="Center"
                                      VerticalOptions="FillAndExpand">
                                    <Label Grid.Row="0" 
                                           Grid.Column="0"
                                           HorizontalOptions="End"
                                           Text="{Binding Current_Id, StringFormat='Current: {0}'}"/>
                                    <Label Grid.Row="0" 
                                           Grid.Column="1"
                                           HorizontalOptions="Center"
                                           Text="{Binding Status}"
                                           TextColor="{Binding Status, Converter={StaticResource StatusToColorConverter}}"/>
                                    <StackLayout Grid.Row="0"
                                                 Grid.Column="2"
                                                 Orientation="Vertical"
                                                 VerticalOptions="Center">
                                        <Label Text="{Binding Latitude}"/>
                                        <Label Text="{Binding Longitude}"/>
                                    </StackLayout>
                                </Grid>
                            </StackLayout>
                        </ViewCell>
                    </DataTemplate>
                </ListView.ItemTemplate>
            </ListView>
        </StackLayout>
    </ContentPage.Content>

Picker won't reset with SelectedIndex = -1

$
0
0

Hi everyone,

For a school project I'm working on a Xamarin.Forms app. It is about video games and consoles (called platforms).
In one of my screens I have a ListView that shows the user's platforms and, below, I have a picker that allows the user to add a platform to his collection.

<ListView x:Name="lv_Platforms" x:FieldModifier="public" ItemsSource="{Binding ListOfPlatforms}">
                <ListView.ItemTemplate>
                    <DataTemplate>
                        <local:CustomViewCell SelectedBackgroundColor="LightSkyBlue">
                            <StackLayout Orientation="Horizontal">
                                <Image Source="{Binding PlatformLogo}"/>
                                <StackLayout Orientation="Horizontal">
                                    <Label Text="{Binding Name}" VerticalTextAlignment="Center" HorizontalOptions="Start" Padding="5,0,0,0" FontAttributes="Bold"/>
                                    <ImageButton Source="icon_delete.png" VerticalOptions="Center" Aspect="AspectFit" HorizontalOptions="End" Clicked="RemovePlatform" ></ImageButton>
                                </StackLayout>
                            </StackLayout>
                        </local:CustomViewCell>
                    </DataTemplate>
                </ListView.ItemTemplate>
            </ListView>
            <Picker x:Name="pck_AddPlatform" ItemsSource="{Binding AvailablePlatforms}" ItemDisplayBinding="{Binding Name}" SelectedIndexChanged="AddToUserPlatforms" SelectedItem="{Binding PickedItem, Mode=TwoWay}"></Picker>

When an item is selected in my Picker, I need to remove it so that it cannot be selected again. It works fine, except for the last item in the picker.
Since the method below is executed on SelectedIndexChanged, the picker loops through the other elements in it, until there is none left and it displays an OutofBounds exception (because the picker is then empty).

Code of the method that adds to ListView and removes from Picker :

private void AddToUserPlatforms(object sender, EventArgs e)
        {
            Platform p = (Platform)pck_AddPlatform.SelectedItem;
            if (p != null)
            {
                CustomPlatform NewPlatform = new CustomPlatform(p.Id, p.Name, p.Abbreviation);
                ListOfPlatforms.Add(NewPlatform);
                AvailablePlatforms.Remove(PickedItem);
            }
            pck_AddPlatform.SelectedIndex = -1;
        }

No matter what I tried I couldn't find a way to either deselect the picker's selection or simply not execute my method again.

If anyone could help or suggest an idea it'd be greatly appreciated.
Apologies if something is missing from my post, I don't post often.

Thanks !

Slider design

$
0
0

hi
how create Slider design
Just like the movie

Exactly Zoom and Zoom out image mode

Options for video playback

$
0
0

What are my options for video playback in Xamarin.forms? Searching through the forums, webview seems to be the suggestion alot, but I hate the fact that an app needs to be clunky with an 'iframe' of sorts. Is there a native player that I can use to play YouTube/Vimeo videos directly in both a mini as well as expanded view?

Xamarin certification

$
0
0

Hello, I would like to be certified in Xamarin Forms, is there a website where I can train myself for certification please?


Linker failure using FirebasePushNotificationPlugin

$
0
0

I am using the FirebasePushNotificationPlugin for both iOS and Android. I can successfully build my iOS app and it runs fine and handles push notifications.
However when I try to archive the app for publication the linker fails as some Firebase related symbols are missing.
How can I get the linker to find the symbols.

Delete image in sd card

$
0
0
Hi All,
How to delete image after taking photo using media plugin
Note: Image is in sd card.
Xamarin forms

ANNOUNCEMENT : NEW IAP NUGET PACKAGE

$
0
0

Hi All,

I have been long time using my own IAP implementation for Android and UWP different than existing In app billing packages and finally created a nuget package.
What is different in this package is;

  • Using BillingClient V3 instead of AIDL. I believe code is very simple and for anyone can understand to create PR.
  • UWP uses StoreContext isntead of Application Context old version.
  • IOS nothing new in this here. using James's code.
  • Amazon: I have the code, not merged yet. It is coming during this week.
  • Tizen: Also will be merged this week.

Please feel free to create PRs.

https://www.nuget.org/packages/XFInAppBilling/

Xamarin.Forms for Xamarin.Mac has been in 'preview' for coming up to 3 years. Any end in sight?

$
0
0

Is this yet another case of Xamarin starting a project and abandoning it?

UI not getting update based on async command

$
0
0

Hello,

I am not getting clever why the UI is not getting updated when using async commands - neither based on OnAppearing, nor by pressing the button

View model:

namespace MVVMDataBinding 
{

    public class TaskModel: BaseViewModel
    {
        private string title;
        public string Title
        {
            get { return title; }
            set
            {
                title = value;
                OnPropertyChanged();

            }
        }

        private string duration;
        public string Duration
        {
            get { return duration; }
            set
            {
                duration = value;
                OnPropertyChanged();

            }
        }

        private string state;
        public string State
        {
            get { return state; }
            set
            {
                state = value;
                OnPropertyChanged();

            }
        }

        private ImageSource sunPicture;
        public ImageSource SunPicture
        {
            get { return sunPicture; }
            set
            {
                sunPicture = value;
                OnPropertyChanged();

            }
        }

    }
}

PageViewModel:
Data are visible on app only when use the comment part of code:

namespace MVVMDataBinding
{
    class HomeViewModel
    {
        public TaskModel TaskModel { get; set; }

        public ICommand LoadDataCommand { get; private set; }
        public ICommand GetTextCommand { get; private set; }
        public HomeViewModel()
        {

            LoadDataCommand = new Command(async () => await LoadData());
            LoadDataCommand = new Command(async () => await GetText());

            /*
            TaskModel = new TaskModel
            {
                Title = "Create India",
                Duration = 2,
                State = "Tamil Nadu",
                SunPicture = "Sun_0.png"
            };
            */
        }

        private async Task LoadData()
        {
            await Task.Run(() =>
            {
                TaskModel = new TaskModel
                {
                    Title = "Title added on load",
                    Duration = 2,
                    State = "State1",
                    SunPicture = "Sun_0.png"
                };
            });
        }

        private async Task GetText()
        {

            TaskModel = new TaskModel
            {
                Title = "Title added by button",
                Duration = 2,
                State = "State2",
                SunPicture = "Sun_0.png"
            };

        }
    }
}

namespace MVVMDataBinding
{
    // Learn more about making custom code visible in the Xamarin.Forms previewer
    // by visiting https://aka.ms/xamarinforms-previewer
    [DesignTimeVisible(false)]
    public partial class MainPage : ContentPage
    {
        public MainPage()
        {
            InitializeComponent();

            ViewModel = new HomeViewModel();
        }

        protected override void OnAppearing()
        {
            ViewModel.LoadDataCommand.Execute(null);
            base.OnAppearing();
        }

        private HomeViewModel ViewModel
        {
            get { return BindingContext as HomeViewModel; }
            set { BindingContext = value; }
        }
    }
}

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage
    x:Class="MVVMDataBinding.MainPage"
    xmlns="http://xamarin.com/schemas/2014/forms"
    xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
    xmlns:local="clr-namespace:MVVMDataBinding">


    <StackLayout VerticalOptions="Center">
        <Button Command="{Binding GetTextCommand}" Text="Get Text" />
        <Label Text="Title of the task" />
        <Entry Text="{Binding TaskModel.Title}" />
        <Label Text="Duration of the task" />
        <Entry Text="{Binding TaskModel.Duration}" />
        <Label Text="State of Country" />
        <Entry Text="{Binding TaskModel.State}" />
        <Image Aspect="Fill">
            <Image.Source>
                <FileImageSource File="{Binding TaskModel.SunPicture}" />
            </Image.Source>
        </Image>
    </StackLayout>
</ContentPage>  
Viewing all 77050 articles
Browse latest View live


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