How to enable view in Xamarin forms in NavigationBar?

I need your help!

I am working on a cross-platform mobile development project. I am using Visual Studio with Xamarin Forms. I have a SearchBar (Xamarin.Forms class), but my problem is to include it in the NavigationBar.

I currently have a MasterDetailPage, and I'm initializing this.Detail with a new NavigationPage (new customPage ()). I also have a SearchBar renderer. So, I need the original NavigationBar (I want to keep the return button), but I would like to add my SearchBar inside.

I would really appreciate it if you know a way to do this specifically for Android. Thank you in advance!

+3
source share
1 answer

You need to create a custom NavigationRenderer and insert your own UISearchBar in the UIToolbar or SearchView in the ViewGroup :

Xamarin Forms: Renderer Base Classes and Native Controls

As an example, insert an iOS UISearchBar into the navigation bar through a custom NavigationRenderer :

enter image description here

Note. In order for everything to be untied, the use of MessagingCenter allows you to send messages around without any dependencies of hard-coding events in the user renderer.

 [assembly:ExportRenderer (typeof(NavigationPage), typeof(SeachBarNavigationRender))] namespace Forms.Life.Cycle.iOS { public class SeachBarNavigationRender : NavigationRenderer { public SeachBarNavigationRender () : base() { } public override void PushViewController (UIViewController viewController, bool animated) { base.PushViewController (viewController, animated); List<UIBarButtonItem> toolbarItem = new List<UIBarButtonItem> (); foreach (UIBarButtonItem barButtonItem in TopViewController.NavigationItem.RightBarButtonItems) { if ( barButtonItem.Title.Contains( "search")) { UISearchBar search = new UISearchBar (new CGRect (0, 0, 200, 25)); search.BackgroundColor = UIColor.LightGray; search.SearchBarStyle = UISearchBarStyle.Prominent; search.TextChanged += (object sender, UISearchBarTextChangedEventArgs e) => { D.WriteLine(e.SearchText); MessagingCenter.Send<object, string> (this, "SearchText", e.SearchText); }; barButtonItem.CustomView = search; } toolbarItem.Add (barButtonItem); } TopViewController.NavigationItem.RightBarButtonItems = toolbarItem.ToArray (); } } } 
+4
source

Source: https://habr.com/ru/post/983787/


All Articles