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

Get a font exception if not in Navigation page

$
0
0

I had a Xamarin.Forms application which had a tool bar, so the MainPage was wrapped with a Navigation page (for having
this tool bar). Everything worked well.

Now, I try to convert this application to be a MasterDetail Page application.
Therefore I don't need the Navigation page (If I use the Navigation Page I will have two toolbars, and I don't want it).

The problem is that when I launch MasterDetailPage not wrapped with a Navigation page (From App.cs)
I get the exception:
" Java.Lang.RuntimeException: 'Font asset not found sans-serif' "
in MainActivity.cs

I've checked in all the solution: I don't use any font with the name 'sans-serif'.

for summary:~~~~
In App.xaml.cs:
MainPage = new NavigationPage(new NiceMasterDetailPage());
doesn't provide any exception.

In App.xaml.cs:
MainPage = new NiceMasterDetailPage();
does provide the exception:
" Java.Lang.RuntimeException: 'Font asset not found sans-serif' "

Does someone can help me understand why?


Re-Highlight CollectionView SelectedItems?

$
0
0

Hello, I have been struggling to make my inventory lists maintain consistent highlighted items when using a SearchBar or sometime navigating away from the page. I see this great looking sample from the MS Docs' "Xamarin.Forms CollectionView Selection : Multiple Pre-Selection" (I can't post links here, yet)

<CollectionView x:Name="collectionView"
                ItemsSource="{Binding Monkeys}"
                SelectionMode="Multiple"
                SelectedItems="{Binding SelectedMonkeys}">
    ...
</CollectionView>


namespace CollectionViewDemos.ViewModels
{
    public class MonkeysViewModel : INotifyPropertyChanged
    {
        ...
        ObservableCollection<object> selectedMonkeys;
        public ObservableCollection<object> SelectedMonkeys
        {
            get
            {
                return selectedMonkeys;
            }
            set
            {
                if (selectedMonkeys != value)
                {
                    selectedMonkeys = value;
                }
            }
        }

        public MonkeysViewModel()
        {
            ...
            SelectedMonkeys = new ObservableCollection<object>()
            {
                Monkeys[1], Monkeys[3], Monkeys[4]
            };
        }
        ...
    }
}

However, I'm not assigning by index numbers... really I'm just trying to say:

SelectedMonkeys = SelectedMonkeys ;
_ SelectedMonkeys are still SelectedMonkeys _

But how do I make that work? I tried this without success:

SelectedItems="{Binding SelectedMonkeys, Mode=TwoWay}"

Thanks!

Load Application(new App())

$
0
0

Hey developers
I am facing an issue for Load Application(new App())
`
using Android.App;
using Android.Content.PM;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.OS;

namespace Iot.Droid
{
[Activity(Label = "Iot", Icon = "@mipmap/icon", Theme = "@style/MainTheme", MainLauncher = true, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation)]
public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity
{
protected override void OnCreate(Bundle savedInstanceState)
{
TabLayoutResource = Resource.Layout.Tabbar;
ToolbarResource = Resource.Layout.Toolbar;

        base.OnCreate(savedInstanceState);

        Xamarin.Essentials.Platform.Init(this, savedInstanceState);
        global::Xamarin.Forms.Forms.Init(this, savedInstanceState);
        LoadApplication(new App());
    }
    public override void OnRequestPermissionsResult(int requestCode, string[] permissions, [GeneratedEnum] Android.Content.PM.Permission[] grantResults)
    {
        Xamarin.Essentials.Platform.OnRequestPermissionsResult(requestCode, permissions, grantResults);

        base.OnRequestPermissionsResult(requestCode, permissions, grantResults);
    }
}

}`
It throws a missing assembly exception

BuildFailed in Release Mode Android in Xamarin forms (Mac)

$
0
0

Hello There,I am not able to build the android project in xamarin forms (Mac) in Release Mode and getting below error, could you please help me?
FYI, I am able to build in Debug mode.
/Library/Frameworks/Mono.framework/External/xbuild/Xamarin/Android/Xamarin.Android.Common.targets(5,5): Error XALNK7000: Mono.Linker.MarkException: Error processing method: 'Com.Microsoft.Appcenter.Http.IServiceCall Com.Microsoft.Appcenter.Data.Client.CosmosDb::CallCosmosDbApi(Com.Microsoft.Appcenter.Data.Models.TokenResult,System.String,Com.Microsoft.Appcenter.Http.IHttpClient,System.String,System.String,Com.Microsoft.Appcenter.Http.IServiceCallback)' in assembly: 'Microsoft.AppCenter.Data.Android.Bindings.dll' ---> Mono.Cecil.ResolutionException: Failed to resolve Com.Microsoft.Appcenter.Http.IHttpClient
at Mono.Linker.Steps.MarkStep.HandleUnresolvedType (Mono.Cecil.TypeReference reference) [0x00013] in <0d3a2268388448fdb90b4a54c411a87d>:0
at Mono.Linker.Steps.MarkStep.MarkType (Mono.Cecil.TypeReference reference) [0x0002c] in <0d3a2268388448fdb90b4a54c411a87d>:0
at MonoDroid.Tuner.MonoDroidMarkStep.MarkType (Mono.Cecil.TypeReference reference) [0x00000] in <0d3a2268388448fdb90b4a54c411a87d>:0
at Mono.Linker.Steps.MarkStep.ProcessMethod (Mono.Cecil.MethodDefinition method) [0x000c8] in <0d3a2268388448fdb90b4a54c411a87d>:0
at Mono.Linker.Steps.MarkStep.ProcessQueue () [0x0001b] in <0d3a2268388448fdb90b4a54c411a87d>:0
--- End of inner exception stack trace ---
at Mono.Linker.Steps.MarkStep.ProcessQueue () [0x00047] in <0d3a2268388448fdb90b4a54c411a87d>:0
at Mono.Linker.Steps.MarkStep.ProcessPrimaryQueue () [0x0000a] in <0d3a2268388448fdb90b4a54c411a87d>:0
at Mono.Linker.Steps.MarkStep.Process () [0x000f6] in <0d3a2268388448fdb90b4a54c411a87d>:0
at Mono.Linker.Steps.MarkStep.Process (Mono.Linker.LinkContext context) [0x0000d] in <0d3a2268388448fdb90b4a54c411a87d>:0
at MonoDroid.Tuner.MonoDroidMarkStep.Process (Mono.Linker.LinkContext context) [0x0000b] in <0d3a2268388448fdb90b4a54c411a87d>:0
at Mono.Linker.Pipeline.ProcessStep (Mono.Linker.LinkContext context, Mono.Linker.Steps.IStep step) [0x0000d] in <0d3a2268388448fdb90b4a54c411a87d>:0
at Mono.Linker.Pipeline.Process (Mono.Linker.LinkContext context) [0x0000f] in <0d3a2268388448fdb90b4a54c411a87d>:0
at MonoDroid.Tuner.Linker.Run (Mono.Linker.Pipeline pipeline, Mono.Linker.LinkContext context) [0x00000] in <0d3a2268388448fdb90b4a54c411a87d>:0
at MonoDroid.Tuner.Linker.Process (MonoDroid.Tuner.LinkerOptions options, Mono.Linker.ILogger logger, Mono.Linker.LinkContext& context) [0x00071] in <0d3a2268388448fdb90b4a54c411a87d>:0
at Xamarin.Android.Tasks.LinkAssemblies.Execute (Java.Interop.Tools.Cecil.DirectoryAssemblyResolver res) [0x001dd] in <0d3a2268388448fdb90b4a54c411a87d>:0
at Xamarin.Android.Tasks.LinkAssemblies.RunTask () [0x0001b] in <0d3a2268388448fdb90b4a54c411a87d>:0
at Xamarin.Android.Tasks.AndroidTask.Execute () [0x00000] in <0d3a2268388448fdb90b4a54c411a87d>:0 (XALNK7000) (ManaSai.Android)

Thank you in advance

BLE HELP: Only getting the value the second time the method is called?

$
0
0

Hi,
I am currently developing a BLE App using this BLE plugin. What I am trying to do is that when the user presses "Battery" (item in a TableView) the Battery_Tapped event handler gets fired. In this event handler I am trying to send 3 bytes to the device connected to the BLE and the device should send the battery level back. This works (I have tested it), but for some reason the event handler does not receive the byte the first time it gets fired. But if i go back to the status page and click "Battery" again, this time the byte is received (unsure if it is the previous one or a new one being received).
Here is my code for the Battery_Tapped event handler:

private async void Battery_Tapped(object sender, EventArgs e)
        {
            await Navigation.PushAsync(BatteryPage);
            try
            {
                Xamarin.Forms.Device.BeginInvokeOnMainThread(async () =>
                {
                    await App.writeCharacteristic.WriteAsync(BatteryTxBytes);
                });
            }
            catch (Exception ex)
            {
                await DisplayAlert("Notice", ex.Message.ToString(), "Eor !");
            }

            try
            {
                App.readCharacteristic.ValueUpdated += (o, args) =>
                {
                    BatteryRxBytes = args.Characteristic.Value;
                };
                await App.readCharacteristic.StartUpdatesAsync();

            }
            catch (Exception ex)
            {
                await DisplayAlert("Notice", ex.Message.ToString(), "Error !");
            }
            try
            {
                BatteryPage.UpdateBatteryLevel(BatteryRxBytes[0]);
            }
            catch(Exception ex)
            {
                await DisplayAlert("Notice", ex.Message.ToString(), "ye");
            }
        }

I am suspecting it might have something to do with the await operators, but I am fairly new to Xamarin and C# so I am not sure how to work around this. Any help would be highly appreciated!
Thanks,
Sophie

Access AppThemeBinding in App.xaml with C#

$
0
0

Hi!

I asked this kind of question before, but I was too quick with marking the solution.
I'm using AppThemeBinding to respond to the dark theme on a device. I put all the colors in App.xaml and then I using static resource to access the style:

In some pages I also have a label which changes the color to red when something is wrong. The thing here is that red on a dark background is not helping, so I decided to make this color yellow. This is what I asked before and this was answered: https://forums.xamarin.com/discussion/185226/access-appthemebinding-in-app-xaml-with-c#latest

Now I face the following problem with this: how to do this in the next example?

I hope someone can help.

Is there a way to keep the keyboard open?

$
0
0

I have a simple Chat view with an Editor and a Button.
Is there a way to keep the keyboard opened when I press the button?

I can call the Editor's Focus function, but the feeling about the keyboard going down and up again is awful

Unable to Write and read in plugin BLE

$
0
0

Unable to read the values from read characteristic. Correct me if I'm wrong in code. or provide me the code snippet for better understanding

` var services = await connectedDevice.GetServicesAsync();

    var serviceid = services[0].Id;

    var service = await connectedDevice.GetServiceAsync(serviceid);

    var characteristics = await service.GetCharacteristicsAsync();

    var characteristicread= await service.GetCharacteristicAsync(characteristics[1].Id);

    var characteristicWrite = await service.GetCharacteristicAsync(characteristics[0].Id);

    byte[] bytes = Encoding.ASCII.GetBytes("LIST_DIR,audio");

    await characteristicWrite.WriteAsync(bytes);
    characteristicread.ValueUpdated += (s, ee) =>
        {
            var result = ee.Characteristic.Value;
            var stre = System.Text.Encoding.UTF8.GetString(result, 0, result.Length);
           //i can't able read charecterstic
        };
        await characteristicread.StartUpdatesAsync();`


here is no value updated in the characteristics. Please guide
i got this exception after read
Objective-C exception thrown. Name: NSInternalInconsistencyException Reason: Client Characteristic Configuration descriptors must be configured using setNotifyValue:forCharacteristic:


Please help me to setup the Xamarin.Firebase.Crashlytics 117.0.0-preview02 in xamarin forms project

$
0
0

Hi
In my application i have integrated firebase analytics and crashlytics. in that xamarin.nadroid.crashlytics package will be deprecated on Nov 15, 2020. Hence i am trying to use Xamarin.Firebase.Crashlytics 117.0.0 - preview02 for firebase crashlytics. Please help me to setup the Xamarin.Firebase.Crashlytics 117.0.0 - preview02 in xamarin forms project.

Shell.Current.GoToAsync not working

$
0
0

Hello,
I have written the following code to handle application initialization, I will post only the relevant code snippets:
` public partial class App : Application
{
private System.Timers.Timer connectivityTimer = new System.Timers.Timer();
private System.Timers.Timer timeoutTimer = new System.Timers.Timer();

public static event EventHandler<AppInitEventArgs> Initialized;
    protected virtual void OnInitializeFinished(AppInitEventArgs e)
    {
        Initialized?.Invoke(this, e);
    }

public App()
{
    InitializeComponent();
            MainPage = new AppShell();
         Shell.Current.GoToAsync("loading");
}

public void AppInit()
    {
        connectivityTimer.Interval = 2000;
        connectivityTimer.Elapsed += ConnectivityTimer_Elapsed;
        connectivityTimer.Start();

        timeoutTimer.Interval = 60000;
        timeoutTimer.Elapsed += TimeoutTimer_Elapsed;
        timeoutTimer.Start();
        return;

    }

    private void TimeoutTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
    {
        timeoutTimer.Stop();
        //timeoutTimer.Dispose();
        connectivityTimer.Stop();
        //connectivityTimer.Dispose();

        AppInitEventArgs args = new AppInitEventArgs();

        var access = Connectivity.NetworkAccess;
        if (access == NetworkAccess.None && access == NetworkAccess.Unknown && access == NetworkAccess.ConstrainedInternet)
        {
            args.data = AppInitResult.NoInternet;
        }
        else
        {
            args.data = AppInitResult.Timeout;
        }

        OnInitializeFinished(args);
        return;

    }

private async void ConnectivityTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
    {
        connectivityTimer.Stop();
        var access = Connectivity.NetworkAccess;
        if (access == NetworkAccess.Internet)
        {
            try
            {
                if (Service.HasCredentials == true)
                {
                    JwtModel jwt = await Service.AuthenticateSilent();
                    if (jwt != null)
                    {
                        if (jwt.User.Activated == true)
                        {
                            await GetDevices();
                            await MQTTClient.Init();
                            await MQTTClient.Connect();

                            if (RegisteredDevices.Count == 0)
                            {
                                //inform VM to navigate to add device page
                                AppInitEventArgs args = new AppInitEventArgs();
                                args.data = AppInitResult.NoRegisteredDevices;
                                OnInitializeFinished(args);
                            }
                            else
                            {
                                if (Service.User.PrimaryDeviceId == 0)
                                {
                                    //set first device as registered
                                    User usr = await Service.SePrimaryDevice(App.Service.User, RegisteredDevices[0].DeviceTR.Device.Id);
                                    if (usr != null)
                                    {
                                        Service.User.PrimaryDeviceId = usr.PrimaryDeviceId;
                                    }
                                }
                                AppInitEventArgs args = new AppInitEventArgs();
                                args.data = AppInitResult.Ok;
                                OnInitializeFinished(args);
                            }
                        }
                        else
                        {
                            //inform VM to navigate to login
                            AppInitEventArgs args = new AppInitEventArgs();
                            args.data = AppInitResult.AccountNotActivated;
                            OnInitializeFinished(args);
                        }
                    }
                }
                else
                {
                    //inform VM to navigate to login
                    AppInitEventArgs args = new AppInitEventArgs();
                    args.data = AppInitResult.NoSavedCredentials;
                    OnInitializeFinished(args);
                }
            }
            catch
            {

            }
        }
        else
        {
            connectivityTimer.Start();
            return;
        }
    }

protected override async void OnStart()
    {
        AppInit();
    }

}`

So my logic in the App class is the following: create an Init method that will be called in OnStart(), the Init process triggers an "Initialized" event.
I have created a blank "Initial" XAML page and in its View Model I subscribe to the App.Initialized event. Below is the ViewModel:

`
class InitialViewModel : BaseViewModel
{
public InitialViewModel()
{
Init();
}

    public void Init()
    {
        IsBusy = true;
        App.Initialized += App_Initialized;
    }

    private async void App_Initialized(object sender, AppInitEventArgs e)
    {
        bool ans;
        try
        {
            switch (e.data)
            {
                //IsBusy = false;
                case AppInitResult.Failed:
                    ans = await Application.Current.MainPage.DisplayAlert("Error", "Operation failed!", "Retry", "Cancel");
                    if (ans == true)
                    {

                    }
                    else
                    {

                    }
                    break;
                case AppInitResult.NoInternet:
                    IsBusy = false;
                    ans = await Application.Current.MainPage.DisplayAlert("Error", "No internet connectivity!", "Retry", "Cancel");
                    break;
                case AppInitResult.NoSavedCredentials:
                    await Shell.Current.GoToAsync("login");
                    break;
                case AppInitResult.AccountNotActivated:
                    await Shell.Current.GoToAsync("login");
                    break;
                case AppInitResult.Timeout:
                    IsBusy = false;
                    ans = await Application.Current.MainPage.DisplayAlert("Error", "Operation timeout!", "Retry", "Cancel");
                    break;
                case AppInitResult.NoRegisteredDevices:
                    IsBusy = false;
                    await Shell.Current.GoToAsync("adddevice");;
                    break;
                case AppInitResult.Ok:
                    await Shell.Current.GoToAsync("home");
                    break;
                default:
                    await Shell.Current.GoToAsync("login");
                    break;
            }
        }
        catch (Exception ex)
        {

        }
    }
}`

I ran the App in debug and put breakpoints in the View Model event handler and the triggered events seem to be "intercepted" correctly, but Shell.Current.GoToAsync does nothing, also Application.Current.MainPage.DisplayAlert does nothing.
Any feedback will be appreciated. Also any feedback regarding best practices to application initialize process is welcome.

Forms ListView leaking on Android

$
0
0
Hello,

can someone explain me how to get rid of ListView or CollectionView from Android memory, using XF?
When popping page containing ListView from navigation stack, i can get that page garbage collected but ListView still remains in memory. I think Android renderer is leaking as UWP works as intended.

Binding Activity Indicator to a player

$
0
0

Hello
I just want to know if there is any way to let the activity indicator running until the player is ready or until the player start playing in Xaml or in code behing and stop the activity after.
additional: I'm using mediamanager as player to play some audio.

Using ACR.UserDialogs to display an Alert for specified period

$
0
0

I was looking at using the ACR.UserDialogs to display an alert and then have it dismissed after x number of seconds.

The code in the sample seems pretty convoluted.

var x2 = new Acr.UserDialogs.AlertConfig() { Message = "msg", OkText = "OK", Title = "Answer Title" };
await Acr.UserDialogs.UserDialogs.Instance.AlertAsync(x2);

Displays an alert but I can seem to piece together the additional code to make it dismiss after X seconds.

Any assistance for the extra code ?

Xamarin Forms Collection View Issues with Scroll View

$
0
0

I have a horizontal carousel view with vertical collection view in my screen, I have to use a scroll view for show all of the info, however when come to the scroll of collection view, the parent scroll is not functioning. Any Ideas?

SwipeItemView doesnt run my tap event

$
0
0

I have a SwipeItemView in a listview and inside a stacklayout with two frames.
The problem is that it doesn't always work the tap event.

<ListView.ItemTemplate>
                <DataTemplate>
                    <ViewCell>
                        <SwipeView>

                            <SwipeView.RightItems>
                                <SwipeItems>
                                    <SwipeItemView>
                                        <StackLayout 
                                             Spacing="12"
                                             BackgroundColor="#f0f0f0"
                                             Orientation="Horizontal">
                                            <local:CustomFrame 
                                                 Margin="15,0,0,0"
                                                 WidthRequest="40"
                                                 HeightRequest="40"
                                                 BackgroundColor="Wheat"
                                                 touch:TouchEff.NativeAnimation="True"
                                                 Padding="0" 
                                                 VerticalOptions="Center"
                                                 HorizontalOptions="Center"
                                                 HasShadow="True" 
                                                 CornerRadius="10">
                                                <ffSvg:SvgCachedImage
                                                      Margin="10"
                                                      FadeAnimationEnabled="False"
                                                      FadeAnimationDuration="0"
                                                      LoadingDelay="0"
                                                      Source="imgEdit.svg"
                                                      VerticalOptions="FillAndExpand"
                                                      HorizontalOptions="FillAndExpand"/>
                                                <local:CustomFrame.Effects>
                                                    <touch:TouchEff Completed="Edit_Event" />
                                                </local:CustomFrame.Effects>
                                            </local:CustomFrame>
                                            <local:CustomFrame 
                                                Margin="0,0,15,0"
                                                WidthRequest="40"
                                                HeightRequest="40"
                                                BackgroundColor="Wheat"
                                                touch:TouchEff.NativeAnimation="True"
                                                Padding="0" 
                                                VerticalOptions="Center"
                                                HorizontalOptions="Center"
                                                HasShadow="True" 
                                                CornerRadius="10">
                                                <ffSvg:SvgCachedImage
                                                      Margin="10"
                                                      FadeAnimationEnabled="False"
                                                      FadeAnimationDuration="0"
                                                      LoadingDelay="0"
                                                      Source="imgDelete.svg"
                                                      VerticalOptions="FillAndExpand"
                                                      HorizontalOptions="FillAndExpand"/>
                                                <local:CustomFrame.Effects>
                                                    <touch:TouchEff Completed="Delete_Event"/>
                                                </local:CustomFrame.Effects>
                                            </local:CustomFrame>
                                        </StackLayout>
                                    </SwipeItemView>
                                </SwipeItems>
                            </SwipeView.RightItems>

                            <StackLayout  Spacing="0">
                                <StackLayout 
                                    Margin="10" 
                                    Spacing="0" 
                                    Orientation="Horizontal">
                                <Label 
                                    WidthRequest="40"
                                    MinimumWidthRequest="40"
                                    HorizontalTextAlignment="Start"
                                    Text="{Binding Quantity, StringFormat='x{0:0.###}'}" 
                                    HorizontalOptions="Start" 
                                    FontSize="Subtitle" 
                                    TextColor="Black"/>
                                <StackLayout
                                        Spacing="0"
                                        HorizontalOptions="Center" >
                                    <Label 
                                      HorizontalTextAlignment="Start"
                                      Text="{Binding Name}" 

                                      FontSize="Subtitle" 
                                      TextColor="Black"/>
                                    <Label
                                         HorizontalTextAlignment="Start"
                                         Text="{Binding Extras}" 
                                         FontSize="Small"
                                         TextColor="Gray">
                                        <Label.Triggers>
                                            <DataTrigger 
                                                    TargetType="Label"
                                                    Binding="{Binding Path=Extras}" 
                                                    Value="">
                                                <Setter 
                                                    Property="Text" 
                                                    Value="{Binding MainItemComments}" />
                                            </DataTrigger>
                                        </Label.Triggers>

                                    </Label>
                                </StackLayout>
                                <Label  
                                        HorizontalTextAlignment="End"
                                        Text="{Binding SumPrice, StringFormat='{0:0.00}€'}"
                                        MinimumWidthRequest="60"
                                        WidthRequest="60"
                                        HorizontalOptions="EndAndExpand" 
                                        FontSize="Subtitle" 
                                        TextColor="Black"/>
                            </StackLayout>




                        </StackLayout>

                        </SwipeView>
                    </ViewCell>
                </DataTemplate>   

I noticed that it works only if i will use Invoked event on swipeview. Is this right? How can i detect which frame is been pressed in Invoked event?


How can I get lat long from place id?

$
0
0

"predictions": [
{
"description": "Shwe Phu Myaw Street, Yangon, Myanmar (Burma)",
"place_id": "Ei1TaHdlIFBodSBNeWF3IFN0cmVldCwgWWFuZ29uLCBNeWFubWFyIChCdXJtYSkiLiosChQKEgm9dYxo3-zBMBG33fzZM-fi4RIUChIJaxk-Ip6UwTARtAsI-HHS-1Y"
}
],

I want latitude and longitude from place_id.

Home Page Design

$
0
0

Hi Guys,
I'm looking same design for Xamarin forms which i attached in the question.
Did any one have idea on this design . Kindly recommended me.

Thanks,
Vasanth

DataGrid: [Android][UWP] Header text for some languages are not properly rendered

$
0
0

I'm developing multi lingual app using Xamarin and I have an Issue with displaying the header text for RadaDataGrid only for Japanese language. Issue is text displayed as boxes on grid header when language is Japanese. for other controls like button, label, entry are fine. Here I have attached the image. Can any one help to solve.

How to implement SearchBar properly? Where's my conflict?

$
0
0

I am trying to implement a Xamarin.Forms search bar with realtime results, but have found very little success! Can you please help me understand how to make one of these approaches work? All scenarios are based on "Xamarin.Forms - SearchBar Demos" from MS Docs (I cannot post links, yet).

Note about my ViewModel:

I have been using this INotifyPropertyChanged implementation, which I do not believe would interfere with intended search bar operation:

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

Adding the MS Docs sample version's has not seemed to change anything.

1) Based on sample "SearchBarXamlMvvmPage"
Does not search in realtime,
Does not allow search to clear or reset,
"Search Button" and "Clear Search Button" do not seem to trigger any command or event
CollectionView loses highlighted items after SearchCommand

My Xaml:

        <SearchBar x:Name="searchBar"
            Placeholder="Search..."
            SearchCommand="{Binding SearchCommand}" 
            SearchCommandParameter="{Binding Text, Source={x:Reference searchBar}}"/>    
        <CollectionView                 
            x:Name="MyListView"
            ItemsSource="{Binding MyList}"
            SelectionMode="Multiple"            
            SelectedItem="{Binding MySelectedItem, Mode=TwoWay}"
            SelectedItems="{Binding MySelectedItems, Mode=TwoWay}"                        
            SelectionChangedCommand="{Binding MySelectionChangedCommand}">            
            <CollectionView.ItemTemplate>
                <DataTemplate>
                    <Grid...etc...

My View Model:

public ICommand SearchCommand { get; }
        //in constructor...
        SearchCommand = new Command<string>(OnSearchCommand);
        //related method
        public void OnSearchCommand(string query)
        {  
            MyList = new ObservableCollection<MyClass>(App.MyDataService.GetByQueryAsync(query).Result);         
        }

2) Based on "SearchBarXamlPage"
Fails in all the same ways as effort #1

My Xaml:

<SearchBar x:Name="searchBar"
    SearchButtonPressed="OnSearchButtonPressed"/>
<CollectionView etc...


My Xaml.cs:
void OnSearchButtonPressed(object sender, EventArgs e)
{
    ViewModelLocator.MyListVM.OnSearchCommand(searchBar.Text); 
    //(ViewModelLocator = static class contains one of each view model)
}

This View Model is the same as above.

3) Attempting an Event-to-Command Behavior
Does not trigger command in View Model, so there is no function

My Behavior:

public class EventToCommandBehavior : BindableBehavior<View>
    {
        public static BindableProperty EventNameProperty =
            BindableProperty.CreateAttached("EventName", typeof(string), typeof(EventToCommandBehavior), null,
                BindingMode.OneWay);

        public static BindableProperty CommandProperty =
            BindableProperty.CreateAttached("Command", typeof(ICommand), typeof(EventToCommandBehavior), null,
                BindingMode.OneWay);

        public static BindableProperty CommandParameterProperty =
            BindableProperty.CreateAttached("CommandParameter", typeof(object), typeof(EventToCommandBehavior), null,
                BindingMode.OneWay);                
                etc...

My Xaml:

  <SearchBar x:Name="searchBar">
            <SearchBar.Behaviors>
                <behaviors:EventToCommandBehavior
                    EventName="TextChanged"
                    Command="{Binding SearchCommand}"
                    CommandParameter="{Binding Source={x:Reference searchBar}, Path=Text}">                        
                </behaviors:EventToCommandBehavior>                    
            </SearchBar.Behaviors>
        </SearchBar>
        <CollectionView etc...

This View Model is the same as above.

I had a home-brewed search entry working real time, but it also forgets which items are selected if I navigate away, so I'm back to fighting with the built-in product. Any help would be appreciated! Thanks!

Xamarin Forms Android Camera not working after update Android OS 11

Viewing all 91519 articles
Browse latest View live


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