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

How do I dynamically update a list of online users in my signalr-based app?

$
0
0

Heyo, newbie to Xamarin.Forms, and among all my searching I cannot seem to find an answer to this (seemingly) simple question... How do I show a list of online users of my service, and update that list as users log on and off? The scenario I am trying to accomplish is that the user is sitting on the page that shows the list of users currently online, and I would like to see this binding updated dynamically as other users log on and off (i.e., the user sees names being added to and removed from the page).

For the details of my implementation...

When my user logs into my app, a signalR connection is made which passes back a list of other users who are online. This list is stored as a static variable that is defined in App.xaml.cs and is used to populate an ObservableCollection called UsersOnlineList that is then bound to my ListView.

ChatUser.cs

    public class ChatUser
    {
        public int UserId {get; set;}
        public string UserName { get; set; }

        public ChatUser()
        {

        }
    }

App.xaml.cs

public static List<ChatUser> ConnectedUsers { get; set; }

GroupedList.cs

    public class GroupedList: List<ChatUser>
    {
        public string GroupHeader { get; set; }
        public List<ChatUser> Users => this;
    }

UsersOnlineViewModel.cs

        public ObservableCollection<GroupedList> UsersOnlineList { get; set; }

UsersOnlinePage.xaml

<ContentPage.Content>
        <StackLayout>
            <ListView x:Name="MyListView" 
                ItemsSource="{Binding UsersOnlineList}"
                      IsGroupingEnabled="True"
                VerticalOptions="FillAndExpand"
                 HasUnevenRows="true"
                      RefreshCommand="{Binding LoadUsersCommand}"
                      IsPullToRefreshEnabled="true"
                      IsRefreshing="{Binding IsBusy, Mode=TwoWay}"
                 CachingStrategy="RecycleElement"
                 ItemSelected="OnItemSelected">
                <ListView.GroupHeaderTemplate>
                    <DataTemplate>
                        <ViewCell>
                            <Label Text="{Binding GroupHeader}" />
                        </ViewCell>
                    </DataTemplate>
                </ListView.GroupHeaderTemplate>
                <ListView.ItemTemplate>
                    <DataTemplate>
                        <ViewCell>
                            <StackLayout Padding="10">
                                <Label Text="{Binding UserName}" 
                       LineBreakMode="NoWrap" 
                       Style="{DynamicResource ListItemTextStyle}" 
                       FontSize="16" />
                            </StackLayout>
                        </ViewCell>
                    </DataTemplate>
                </ListView.ItemTemplate>
            </ListView>
        </StackLayout>
    </ContentPage.Content>

FYI, the reason I am going from the "global" App.ConnectedUsers List to the ObservableCollection is so that I can define a heading for grouping purpose, as well as do a little re-organization of the list of online users before it is displayed in the app.

If another user logs on or off, a signalR call will be sent to all connected clients denoting the user that logged on or off.

HubManager.cs

            AppHubProxy.On<ChatUser>("onUserDisconnected", (cu) =>
            {
                int cuIdx = App.ConnectedUsers.FindIndex(obj => obj.UserId == cu.UserId);
                if (cuIdx > -1)
                {
                    App.ConnectedUsers.RemoveAt(cuIdx);
                }
            });

What I am missing is how do I go from the onUserDisconnected callback occurring to updating the UsersOnlineList that binds to the ListView?

As a newbie, I am 100% open to different implementations that accomplish what I am trying to do more efficiently

Thank you in advance!


Picker - Binding Context

$
0
0

Currently have a picker that won't display the list of items that are bound to it.

I have a ListView that is using the exact same binding, and it displays the list no problems at all.

Code below:

        <StackLayout IsVisible="{Binding IsDropdownControl}">
          <Label Text="Task Field:"/>
          <Picker Title="Select a Value:"
                        ItemsSource="{Binding FieldItems}" BindingContext="{Binding SelectedField}"
                        ItemDisplayBinding="{Binding Name}"
                  SelectedItem="{Binding SelectedFieldItem}"
                  HorizontalOptions="FillAndExpand">
          </Picker>
        </StackLayout>


        <StackLayout IsVisible="{Binding IsCheckBoxControl}">
          <Label Text="Select Options:"/>
          <ListView ItemsSource="{Binding FieldItems}" BindingContext="{Binding SelectedField}"
                HasUnevenRows="True"
                SeparatorColor="Gray"
                VerticalOptions="FillAndExpand"
                HorizontalOptions="FillAndExpand">
            <ListView.ItemTemplate>
              <DataTemplate>
                <ViewCell>
                  <StackLayout HorizontalOptions="FillAndExpand" Orientation="Horizontal">
                    <Label Text="{Binding Name}" TextColor="Black" FontSize="Small" 
                             HorizontalOptions="StartAndExpand"/>
                    <Switch HorizontalOptions="End" 
                              IsToggled="{Binding Value}"/>
                  </StackLayout>
                </ViewCell>
              </DataTemplate>
            </ListView.ItemTemplate>
          </ListView>
        </StackLayout>

Editor not sizing properly

$
0
0

I would like the Editor to autoSize and display the whole text. What happens now is when I display a large text in the editor (Lorem Ipsum....) the editor displays only 1 or 1 and a half line and I have to scroll inside the Editor. When I start editing and add a newline/enter, the Editor size jumps to the correct size displaying the whole text.

For iOS I have also tried creating a customRenderer (iOS) setting Control.ScrollEnabled = false; and Control.SizeToFit(); and that seems to work the first time but after editing a while, the Editor size jumps back to 1 line. tapping return on the keyboard the editor jumps back to full size. The AutoSize property does not seem do much either.

On Android it is a different story: the text is visible but it doesn't fit in the editor entirely, I have a feeling that the Editor height is calculated by multiplying the number if linbreaks, which results in the text never fitting the control because it does not wrap text.

Does anybody know how to solve this issue?

@Microsoft PS: I am unable to post a question in Chrome (on Mac) anymore? Buttons don't get disabled and the "Category does not exist message" does not display. It does work in Safari.

Xamarin.Forms iOS change Navigation Back text

$
0
0

The iOS has navigation back button behaviour is kind of strange: By default is displays the title of the previous page, but if the title of the current page is to long it displays "Back", no matter what language you have selected on your device. Our customers don't want that.

I came across this post on how to change this behaviour in Xamarin.iOS. But I need to do it in Xamarin.Forms. I know how to make a custom renderer but I don't know how to get to the back button, Anyone who can help?

How to display popup by clicking item in listview?

$
0
0

I want to achieve something like given in screen below
can anyone please suggest or guide how to implement same
thanks in advance

Picker MVVM Two Picker has data relative using Binding

$
0
0

I have a model like this ( City.cs in Modle folder)

public class City
    {
        public int Key { get; set; }
        public string Name { get; set; }
        public List<string> Regions { get; set; }
        public City()
        {
            Regions = Regions ?? new List<string>();
        }
    }

Data like this (ViewModel.cs in ViewModel folder)

public List<City> GetCities()
        {
            var c = new List<City>()
            {
                new City() { Key = 1, Name = "Keelung", Regions = { "CenterK", "EastK", "NorthK", "WestK", "SouthK" } },
                new City() { Key = 2, Name = "Hsinchu", Regions = { "HEast", "HNorth", "HCenter" } },
                new City() { Key = 3, Name = "Chiayi", Regions = { "CEast", "CWest" } }
            };
            return  c;
        }

In my view.xaml is

Picker  x:Name="CityPicker"
                             Title= "City"
                             ItemsSource="{Binding CitiesList}"
                              ItemDisplayBinding="{Binding Name}"
                              SelectedItem="{Binding SelectedCity}"/
 Picker  x:Name="RegionPicker" 
                           Title="Region"
                             BindingContext="{x:Reference CityPicker}"
                               ItemsSource="{Binding MyRegion}"
                              ItemDisplayBinding="{Binding Items}"

In my viewmodel.cs is

 public City SelectedCity
{
    get { return _selectedCity; }
    set
    {
        if (_selectedCity != value)
        {
            _selectedCity = value;
            var _myregion = GetCities().Where(x => x.Name == _selectedCity.Name).Select(s => s.Regions);
            OnPropertyChanged();
        }
    }
}
List<string> _myregion;
public List<string> MyRegion
{
    get { return _myregion; }
    set
    {
        if (_myregion != value)
        {
            _myregion = value;
            OnPropertyChanged();
        }
    }
}
public ClinicSearchStartViewModel()
{
    try
    {
        ClinicListResponses = new ObservableRangeCollection<ClinicListResponse>();
        Title = "Search";
        CitiesList = GetCities().OrderBy(k => k.Key).ToList();

        GetClinicListResponsesCommand = new Command<ClinicSearchRequest>(async (clinicsearchrequest)
            => await GetClinicListResponsesAsync(clinicsearchrequest));
    }
    catch (Exception ex)
    {
        throw;
    }
}

How can write a code to make RegionPicker ItemDisplayBinding show CityPicker SelectedItem related Region
for example
CityPicker Select Keelung then click RegionPicker will show { "CenterK", "EastK", "NorthK", "WestK", "SouthK" }

Thanks for Reading````

Update ListView XAML Programmatically

$
0
0

I am trying to update a ListView's ViewCell using C# code. Basically I want to Iterate through the listview and change the visibility of certain things within the ViewCell. Here's some pseudo code to better represent what I am trying to do.

ListView lv = listviewFromXaml; //get a populated listview from xaml

for (int a =0; a < lv.ItemCount; a++){ //Iterate through list
    if (someBoolean){
    var child = lv.getChild(a); //Get ViewCell by position
        child.exampleLabel.IsVisible = false; //Change something about the view after some simple logic
    }
}

Is Something like this possible in a Cross Platform application? Or am I stuck using Bindings in the XAML?
If it is possible, how would this be done?

Download, save and display Pdf file

$
0
0

I have the following requirements in my xamarin.forms app

  1. I need to download a pdf file from the url on button click
  2. Need to save them locally in defined folder
  3. Then i need to display with installed pdf viewer.

Any help on this? @FredyWenger @MitchMilam


Remove page from Navigation

$
0
0

In my app structure is like below,
List Page -> Detail Page -> Edit Page

and in edit page there is button "Delete" which removes data from database.

Now my problem is to navigate user from Edit page to List Page,

I'm using Navigation.popasync 2 times for this, but on detail page i'm getting error from service that no such record exist.

How can i properly navigate user from Edit page to list page?

How to implement multiple events of the any ui element in viewmodel?

$
0
0

Hi,
I have multiple events of entry to be set like Unfocused, Completed, TextChanged, Focused and so on. How do i assgin the commands to these properties/events to entry? As there cant be more than one command property to an ui element in xaml.

Thanks,

How to Generate HeatMap as shown in image in Xamarin.Forms

$
0
0

Any idea on how to create or implement heatmap in xamarin forms.
i have started by drawing circle using skia.shrp and fill with argb color ,but still not able to do.Any suggestion would be really helpfull

How to change the background color of a button when the mouse is over or is pressed in Xamarin.Forms

$
0
0

I have tried to use Custom Renderer but I can not change the background of the button in uwp, it is always gray. This is what I have done:

public class MyButtonRenderer : ButtonRenderer
{
    protected override void OnElementChanged(ElementChangedEventArgs<Button> e)
    {
        base.OnElementChanged(e);

        if (Control != null)
        {
            Control.Foreground = new SolidColorBrush(Colors.Black);
            Control.BackgroundColor = new SolidColorBrush(Colors.White);
            Control.Background = new SolidColorBrush(Colors.White);
        }
    }

    protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e)
    {
        base.OnElementPropertyChanged(sender, e);
        Control.Foreground = new SolidColorBrush(Colors.Black);
        Control.BackgroundColor = new SolidColorBrush(Colors.White);
        Control.Background = new SolidColorBrush(Colors.White);
    }

}

Any clue or suggestion?

Thanks;

hybridwebview crash Android 9

$
0
0
I have issue with hybridwebview. When i use it on android 9 release app crash. I dont know why. Help me!

ZXing BarcodeWriter issue (string to barcode)

$
0
0

I am trying to create a QR code from a string and not having any luck with either ZXing.Net or ZXing.Net.Mobile.Forms.

I am trying this code with ZXing.Net.Mobile.Forms nuget package.

using System.ComponentModel;
using Xamarin.Forms;
using ZXing;

namespace ZXing {
    [DesignTimeVisible(true)]
    public partial class MainPage : ContentPage {
        public MainPage() {
            InitializeComponent();
            var writer = new BarcodeWriter();
            writer.Format = BarcodeFormat.QR_CODE;
            var barcode = writer.Write("test string");
            // etc
        }
    }
}

I keep getting an error with the red squiggles underneath BarcodeWriter();

Error CS0305 Using the generic type 'BarcodeWriter' requires 1 type arguments ZXing

I also tried the following with no luck

var writer = new ZXing.Mobile.BarcodeWriter();

I have copied the required lines into the Android MainActivity.cs OnCreate and OnRequestPermissionsResult methods. No iOS or UWP, just Android here.

I'm not sure how to remedy this error.

Packages.Config build errors since updating Xamarin forms 3.6.0.344457

$
0
0

Hi,

i recently updated to Xamarin Forms 3.6.0.344457 and since then, my android build no longer builds, the errors are very odd, as in, it looks like packages.config has something wrong with it.

The XML in itself looks ok but upon building, i am getting the errors as identified in the pic.


Is there any sample for use System.Net.Sockets

$
0
0

I need build a network receive loop, it use at Client App.
I use the follow code, but it will block the thread.

            static void Connect(String server, String message)
            {
                try
                {
                    // Create a TcpClient.
                    // Note, for this client to work you need to have a TcpServer 
                    // connected to the same address as specified by the server, port
                    // combination.
                    Int32 port = 30200;
                    TcpClient client = new TcpClient(server, port);

                    // Translate the passed message into ASCII and store it as a Byte array.
                    Byte[] data = System.Text.Encoding.ASCII.GetBytes(message);

                    // Get a client stream for reading and writing.
                    //  Stream stream = client.GetStream();

                    NetworkStream stream = client.GetStream();

                    // Send the message to the connected TcpServer. 
                    stream.Write(data, 0, data.Length);

                    Console.WriteLine("Sent: {0}", message);

                    // Receive the TcpServer.response.

                    // Buffer to store the response bytes.
                    data = new Byte[256];

                    // String to store the response ASCII representation.
                    String responseData = String.Empty;

                    // Read the first batch of the TcpServer response bytes.
                    Int32 bytes = stream.Read(data, 0, data.Length);
                    responseData = System.Text.Encoding.ASCII.GetString(data, 0, bytes);
                    Console.WriteLine("Received: {0}", responseData);

                    // Close everything.
                    stream.Close();
                    client.Close();
                }
                catch (ArgumentNullException e)
                {
                    Console.WriteLine("ArgumentNullException: {0}", e);
                }
                catch (SocketException e)
                {
                    Console.WriteLine("SocketException: {0}", e);
                }

                Console.WriteLine("\n Press Enter to continue...");
                Console.Read();
            }

The code block here, when it timeout the code can go on.

Int32 bytes = stream.Read(data, 0, data.Length);

Because there is no main loop which user can control in Xamarin, so I need a sample to tell me how to build a network receive loop.

I use the TcpClient class.

Button Shadow

$
0
0

I am trying to add a gradient shadow above a button in xamarin forms.For IOS it does work using custom renderer but for android , I can't find a way to make it above and not at the bottom.Any ideas pls.

Seperator lines in TableView

$
0
0

How do I remove the separator lines between each ViewCell in a TableView

I've created this little demo page illustrating the problem:
<br /> <?xml version="1.0" encoding="utf-8" ?><br /> <ContentPage xmlns="http://xamarin.com/schemas/2014/forms" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" x:Class="App29.MainPage"></p> <pre><code><ContentPage.Content> <StackLayout Padding="30" VerticalOptions="Start"> <TableView Intent="Form"> <TableRoot > <TableSection Title="TITLE"> <ViewCell> <Label Text="TEST 1" IsVisible="False"/> </ViewCell> <ViewCell> <Label Text="TEST 2" IsVisible="False"/> </ViewCell> </TableSection> </TableRoot> </TableView> </StackLayout> </ContentPage.Content>


How to play you tube videos in iOS app built by using Xamarin Forms (not Xamarin.iOS)

$
0
0

I want to play you tube videos from a url that i already have. I tried using iframe in custom rendered webview but nothing happens.
Please help me. I am using visual studio 2017 paired with Mac Machine.

How to Add embedded image in Shared project not in PCL?

$
0
0

Hello,

I tried to add embedded image in my shared project.

I created Shared project for Android & IOS.

Added images in shared project.

For rendering, in XAML file :

in same namespace **AllControl **I implemented interface IMarkupExtension.

[Preserve(AllMembers = true)]
[ContentProperty(nameof(Source))]
public class ImageResourceExtension : IMarkupExtension
{
public string Source { get; set; }

    public object ProvideValue(IServiceProvider serviceProvider)
    {
        if (Source == null)
        {
            return null;
        }
        // Do your translation lookup here, using whatever method you require, typeof(ImageResourceExtension).GetTypeInfo().Assembly
        Console.WriteLine(typeof(ImageResourceExtension).GetTypeInfo().Assembly);
        var imageSource = ImageSource.FromFile(Source);
        return imageSource;
    }
}

Set image property Build Action as Embedded resource

Same code is working fine for PCL.

Please give suggestion for Shared project.

Thank you

Viewing all 77050 articles
Browse latest View live


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