I would like to extend all the contentpages in my xamarin.forms app with a native view in UWP. I can basically go to each and every page and embed a native view but i dont want this. I want to know if there is a way to do it using a pagerenderer. I tried doing like below.
my idea was to get current page rendering and extend the content with native view and stacklayout and define app.content again with this change. It works in general. If you run the small test project below, you can see that native UWP FontIcons are displayed for each page but there is a problem, if i navigate same page 2 times in MasterDetail in the attached project, page becomes blank. Why is this happening?
and is the approach below best for my case? I am open for alternative solutions.
[assembly: ExportRenderer(typeof(ContentPage), typeof(App3.UWP.ContentPageRenderer))]
namespace App3.UWP
{
public class ContentPageRenderer : PageRenderer
{
bool isDisposing = false;
protected override void OnElementChanged(ElementChangedEventArgs<Xamarin.Forms.Page> e)
{
base.OnElementChanged(e);
if (isDisposing)
return;
if (e.OldElement != null || Element == null)
{
return;
}
ContentPage page = ((ContentPage)Element);
if (page.Content == null)
return;
var XboxControls = new MyUserControl1();
StackLayout stackLayout = new StackLayout() { Orientation = StackOrientation.Vertical };
stackLayout.Children.Add(page.Content);
stackLayout.Children.Add(XboxControls.ToView());
page.Content = stackLayout;
}
protected override Windows.Foundation.Size ArrangeOverride(Windows.Foundation.Size finalSize)
{
return base.ArrangeOverride(finalSize);
}
protected override void Dispose(bool disposing)
{
isDisposing = disposing;
base.Dispose(disposing);
}
}
Test Project
Related
foreach (var equipment in EquipmentCollection)
{
var control = new EquipmentControl(equipment);
MyStackLayout.Children.Add(control);
}
I am getting this error only in UWP but not in Android. Even in UWP if the list size is small it is working fine.
I have tried few work arounds but still I couldn't able to make it work.
Since there is no UpdateLayout() method for xamarin-forms controls so I tried to use custom renderer for stacklayout and raised a child added event and called UpdateLayout() inside it but still got the crash.
[assembly: ExportRenderer(typeof(CustomStackLayout), typeof(CustomStackLayoutRenderer))]
namespace FO4.UWP.Controls
{
public class CustomStackLayoutRenderer : ViewRenderer<StackLayout, StackPanel>
{
StackPanel stkPanel;
protected override void OnElementChanged(ElementChangedEventArgs<StackLayout> e)
{
base.OnElementChanged(e);
if (e.NewElement != null)
{
CustomStackLayout stkLayout = (CustomStackLayout)e.NewElement;
stkLayout.ChildAdded += StkLayout_ChildAdded;
}
if (e.OldElement != null)
{
CustomStackLayout stkLayout = (CustomStackLayout)e.OldElement;
stkLayout.ChildAdded -= StkLayout_ChildAdded;
}
}
private void StkLayout_ChildAdded(object sender, ElementEventArgs e)
{
this.UpdateLayout();
}
}
}
I develop in Xamarin Forms but I don't target UWP.
Here some suggestions that will maybe help you:
For this kind of need, it is more frequent to use DataBinding through BindableLayout.ItemTemplate and Bindable.ItemsSource like described here: https://learn.microsoft.com/en-us/xamarin/xamarin-forms/user-interface/layouts/bindable-layouts#populate-a-bindable-layout-with-data.
If you don't want to use these mechanism, maybe you can try to use the BatchBegin() and BatchCompleted() method before and after your Loop https://learn.microsoft.com/en-us/dotnet/api/xamarin.forms.visualelement.batchbegin?view=xamarin-forms
The use of a renderer shoud not be required in my opinion...
I have a page in Xamarin.Forms in which I have to show PKPaymentButton by using the same PKPaymentButton class which is a child of UIButton in PassKit.
I have written a custom ButtonRenderer and trying to convert the button into PKPayment button.
I got so far that in custom renderer we can change the appearance of a button but can we use something like creating a new button instance in my case PKPaymentButton and replace it with Button.
UPDATE-
I have achieved this by-
public class ApplePayButtonRenderer : Xamarin.Forms.Platform.iOS.ButtonRenderer
{
protected override void OnElementChanged(ElementChangedEventArgs<Button> e)
{
base.OnElementChanged(e);
if (e.OldElement == null)
{
var button = new PKPaymentButton(PKPaymentButtonType.Buy, PKPaymentButtonStyle.Black);
SetNativeControl(button);
}
}
}
Now I am trying to get its click into Xamarin.Forms
You could use Messaging Center to send message when you click the payment Button.
in Custom Renderer
var button = new PKPaymentButton(PKPaymentButtonType.Buy, PKPaymentButtonStyle.Black);
button.TouchUpInside += Button_TouchUpInside;
SetNativeControl(button);
private void Button_TouchUpInside(object sender, EventArgs e)
{
MessagingCenter.Send<Object>(this,"PayButtonClick");
}
in Forms
Add the following code to the constructor of the ContentPage which contains the Payment Button
public xxxPage()
{
InitializeComponent();
MessagingCenter.Subscribe<Object>(this, "PayButtonClick",(args)=> {
//do some thing you want
});
}
I'm trying to insert a UWP specific child in the custom renderer of a StackLayout.
However, in the sample code below, Control is always null whereas my StackLayout has Children. Maybe StackPanel is not what StackLayout is rendered into in UWP.
public class MyRenderer : ViewRenderer<StackLayout, StackPanel>
{
private bool _childAdded;
protected override void OnElementPropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
{
if (!_childAdded && Control?.Children != null)
{
_childAdded = true;
Control.Children.Insert(0, new Windows.UI.Xaml.Shapes.Rectangle());
}
base.OnElementPropertyChanged(sender, e);
}
}
Some modification in you are cade because you are calling base.OnElementPropertyChanged(sender,e) after code implementation. Just try to use below code.
public class MyRenderer : ViewRenderer<StackLayout, StackPanel>
{
private bool _childAdded;
protected override void OnElementPropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
{
base.OnElementPropertyChanged(sender, e);
if(Control==null)
return;
if (!_childAdded && Control.Children != null)
{
_childAdded = true;
Control.Children.Insert(0, new Windows.UI.Xaml.Shapes.Rectangle());
}
}
}
The StackLayout (Layout) renderer is ViewRenderer and implemented on UWP by FrameworkElement; Renderer Base Classes and Native Controls.
Theoretical renderer:
public class MyRenderer : ViewRenderer<StackLayout, FrameworkElement>
...
Control is always null whereas my StackLayout has Children. Maybe StackPanel.
Derive from official document,
In Xamarin.Forms, all layout classes derive from the Layout<T> class and constrain the generic type to View and its derived types. But the layout of children element is incorrect.
And the match Native control within UWP platform is LayoutRenderer. So it is not inherit StackPanel directly. You could also custom a customrederer like the follow.
[assembly: ExportRenderer(typeof(StackLayout), typeof(ICustomStackLayoutRenderer))]
namespace CustomStackLayoutRenderer.UWP
{
public class ICustomStackLayoutRenderer : ViewRenderer<StackLayout, StackPanel>
{
private bool _childAdded;
protected override void OnElementChanged(ElementChangedEventArgs<StackLayout> e)
{
base.OnElementChanged(e);
if (Control == null)
{
var stacklayout = new StackPanel();
SetNativeControl(stacklayout);
}
if (e.OldElement != null)
{
}
if (e.NewElement != null)
{
if (!_childAdded && Control.Children != null)
{
_childAdded = true;
Control.Children.Insert(0, new Windows.UI.Xaml.Shapes.Rectangle() { Width = 100, Height = 100, Fill = new SolidColorBrush(Colors.Red) });
}
}
}
}
}
For your requirement, the better way is that create a CustomStackLayout inherit StackLayout in Xamarin.Forms, and re-layout your children element in your LayoutChildren override method. For more detail you could refer Creating a Custom Layout.
I have an scrollabe layout with an Editor inside that I'd like to make scrollable or auto resizable to fit the contents.
I can't find how to do it.
I tried a custom renderer but I can't find how to set InputMethods to the Control.
Any ideas?
With the help of this post: https://forums.xamarin.com/discussion/80360/editor-inside-scrollview-not-scrolling
That fixed the scrolling on Android (iOS works by default). It avoids the parent scroll event when touching inside the Editor, triggering only the Editor scroll.
First a class on Android project:
using Android.Views;
namespace MyApp.Droid
{
public class DroidTouchListener : Java.Lang.Object, View.IOnTouchListener
{
public bool OnTouch(View v, MotionEvent e)
{
v.Parent?.RequestDisallowInterceptTouchEvent(true);
if ((e.Action & MotionEventActions.Up) != 0 && (e.ActionMasked & MotionEventActions.Up) != 0)
{
v.Parent?.RequestDisallowInterceptTouchEvent(false);
}
return false;
}
}
}
And then use it on the Android Custom EditorRenderer:
protected override void OnElementChanged(ElementChangedEventArgs<Editor> e)
{
base.OnElementChanged(e);
if (e.OldElement == null)
{
var nativeEditText = (global::Android.Widget.EditText)Control;
//While scrolling inside Editor stop scrolling parent view.
nativeEditText.OverScrollMode = OverScrollMode.Always;
nativeEditText.ScrollBarStyle = ScrollbarStyles.InsideInset;
nativeEditText.SetOnTouchListener(new DroidTouchListener());
//For Scrolling in Editor innner area
Control.VerticalScrollBarEnabled = true;
Control.MovementMethod = ScrollingMovementMethod.Instance;
Control.ScrollBarStyle = Android.Views.ScrollbarStyles.InsideInset;
//Force scrollbars to be displayed
Android.Content.Res.TypedArray a = Control.Context.Theme.ObtainStyledAttributes(new int[0]);
InitializeScrollbars(a);
a.Recycle();
}
}
I am using masterdetail page within this page i am using tabbed page now i want to show toolbar icon and search bar on the top of page.i am able to place toolbar icon but struggling with search bar.how to place it at the top its behavior should match with the search bar in whatsapp app and in youtube app
The WhatsApp search bar is just that, a SearchBar control which you can add to your XAML layout as follows:
<StackLayout>
<SearchBar Placeholder="Search" Text="{Binding Filter}" />
<ListView ItemSource="{Binding Items}">
...
</ListView>
</StackLayout>
Ensure you have a backing property for the filter. You can use the setter of this property to intercept people filtering the data and filter the Items property accordingly.
The YouTube search behaves a bit differently. The toolbar item pops a new screen modally where the search is handled similar to a UISearchController (on iOS). There is no Xamarin Forms drop-in control (that I'm aware of) that does this for you so you'll probably have to roll your own.
We can create a custom renderer on both Xamarin.iOS and Xamarin.Android to accomplish it.
Here's a sample application for reference:
https://github.com/brminnick/GitTrends
And here's a blog post that shows how to add a search bar to a Xamarin.Forms app for both Xamarin.iOS & Xamarin.Android: https://www.codetraveler.io/2019/08/10/adding-a-search-bar-to-xamarin-forms-navigationpage/
App.cs
Use a Xamarin.Forms Platform-Specific to use LargeTitles on the Xamarin.iOS app.
using Xamarin.Forms.PlatformConfiguration;
using Xamarin.Forms.PlatformConfiguration.iOSSpecific;
public class App : Xamarin.Forms.Application
{
public App()
{
var navigationPage = new Xamarin.Forms.NavigationPage(new MyContentPage());
navigationPage.On<iOS>().SetPrefersLargeTitles(true);
MainPage = navigationPage;
}
}
ISearchPage Interface
Create an Interface that can be used across the Xamarin.Forms, Xamarin.Android and Xamarin.iOS projects.
public interface ISearchPage
{
void OnSearchBarTextChanged(in string text);
event EventHandler<string> SearchBarTextChanged;
}
Xamarin.Forms Page
public class MyContentPage : ContentPage, ISearchPage
{
public MyContentPage()
{
SearchBarTextChanged += HandleSearchBarTextChanged
}
public event EventHandler<string> SearchBarTextChanged;
public void OnSearchBarTextChanged(in string text) => SearchBarTextChanged?.Invoke(this, text);
void HandleSearchBarTextChanged(object sender, string searchBarText)
{
//Logic to handle updated search bar text
}
}
iOS Custom Renderer
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UIKit;
using MyNamespace;
using MyNamespace.iOS;
using Xamarin.Forms;
using Xamarin.Forms.Platform.iOS;
[assembly: ExportRenderer(typeof(MyContentPage), typeof(SearchPageRenderer))]
namespace MyNamespace.iOS
{
public class SearchPageRenderer : PageRenderer, IUISearchResultsUpdating
{
readonly UISearchController _searchController;
public SearchPageRenderer()
{
_searchController = new UISearchController(searchResultsController: null)
{
SearchResultsUpdater = this,
DimsBackgroundDuringPresentation = false,
HidesNavigationBarDuringPresentation = false,
HidesBottomBarWhenPushed = true
};
_searchController.SearchBar.Placeholder = string.Empty;
}
public override void ViewDidAppear(bool animated)
{
base.ViewDidAppear(animated);
if (ParentViewController.NavigationItem.SearchController is null)
{
ParentViewController.NavigationItem.SearchController = _searchController;
DefinesPresentationContext = true;
//Work-around to ensure the SearchController appears when the page first appears https://stackoverflow.com/a/46313164/5953643
ParentViewController.NavigationItem.SearchController.Active = true;
ParentViewController.NavigationItem.SearchController.Active = false;
}
}
public override void ViewWillDisappear(bool animated)
{
base.ViewWillDisappear(animated);
ParentViewController.NavigationItem.SearchController = null;
}
public void UpdateSearchResultsForSearchController(UISearchController searchController)
{
if (Element is ISearchPage searchPage)
searchPage.OnSearchBarTextChanged(searchController.SearchBar.Text);
}
}
}
Xamarin.Android Menu XML
In the Xamarin.Android project, in the Resources folder, create a new folder called menu (if one doesn't already exist).
Note: the folder, menu, has a lowercase 'm'
In the Resources > menu folder, create a new file called MainMenu.xml.
Open Resources > menu > MainMenu.xml
In MainMenu.xml add the following code:
<?xml version="1.0" encoding="utf-8" ?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item android:id="#+id/ActionSearch"
android:title="Filter"
android:icon="#android:drawable/ic_menu_search"
app:showAsAction="always|collapseActionView"
app:actionViewClass="android.support.v7.widget.SearchView"/>
</menu>
Xamarin.Android CustomRenderer
Uses the Plugin.CurrentActivity NuGet Package.
using Android.Content;
using Android.Runtime;
using Android.Support.V7.Widget;
using Android.Text;
using Android.Views.InputMethods;
using Plugin.CurrentActivity;
using MyNamespace;
using MyNamespace.Droid;
using Xamarin.Forms;
using Xamarin.Forms.Platform.Android;
[assembly: ExportRenderer(typeof(MyContentPage), typeof(SearchPageRenderer))]
namespace MyNamespace.Droid
{
public class SearchPageRenderer : PageRenderer
{
public SearchPageRenderer(Context context) : base(context)
{
}
protected override void OnAttachedToWindow()
{
base.OnAttachedToWindow();
if (Element is ISearchPage && Element is Page page && page.Parent is NavigationPage navigationPage)
{
//Workaround to re-add the SearchView when navigating back to an ISearchPage, because Xamarin.Forms automatically removes it
navigationPage.Popped += HandleNavigationPagePopped;
navigationPage.PoppedToRoot += HandleNavigationPagePopped;
}
}
//Adding the SearchBar in OnSizeChanged ensures the SearchBar is re-added after the device is rotated, because Xamarin.Forms automatically removes it
protected override void OnSizeChanged(int w, int h, int oldw, int oldh)
{
base.OnSizeChanged(w, h, oldw, oldh);
if (Element is ISearchPage && Element is Page page && page.Parent is NavigationPage navigationPage && navigationPage.CurrentPage is ISearchPage)
{
AddSearchToToolbar(page.Title);
}
}
protected override void Dispose(bool disposing)
{
if (GetToolbar() is Toolbar toolBar)
toolBar.Menu?.RemoveItem(Resource.Menu.MainMenu);
base.Dispose(disposing);
}
//Workaround to re-add the SearchView when navigating back to an ISearchPage, because Xamarin.Forms automatically removes it
void HandleNavigationPagePopped(object sender, NavigationEventArgs e)
{
if (sender is NavigationPage navigationPage
&& navigationPage.CurrentPage is ISearchPage)
{
AddSearchToToolbar(navigationPage.CurrentPage.Title);
}
}
void AddSearchToToolbar(string pageTitle)
{
if (GetToolbar() is Toolbar toolBar
&& toolBar.Menu?.FindItem(Resource.Id.ActionSearch)?.ActionView?.JavaCast<SearchView>().GetType() != typeof(SearchView))
{
toolBar.Title = pageTitle;
toolBar.InflateMenu(Resource.Menu.MainMenu);
if (toolBar.Menu?.FindItem(Resource.Id.ActionSearch)?.ActionView?.JavaCast<SearchView>() is SearchView searchView)
{
searchView.QueryTextChange += HandleQueryTextChange;
searchView.ImeOptions = (int)ImeAction.Search;
searchView.InputType = (int)InputTypes.TextVariationFilter;
searchView.MaxWidth = int.MaxValue; //Set to full width - http://stackoverflow.com/questions/31456102/searchview-doesnt-expand-full-width
}
}
}
void HandleQueryTextChange(object sender, SearchView.QueryTextChangeEventArgs e)
{
if (Element is ISearchPage searchPage)
searchPage.OnSearchBarTextChanged(e.NewText);
}
Toolbar GetToolbar() => CrossCurrentActivity.Current.Activity.FindViewById<Toolbar>(Resource.Id.toolbar);
}
}
Sample App
Here's a sample app for reference:
https://github.com/brminnick/GitTrends
And a blog post that shows how to add a search bar for both Xamarin.iOS and Xamarin.Android: https://www.codetraveler.io/2019/08/10/adding-a-search-bar-to-xamarin-forms-navigationpage/
Used User Control for Navbar. and hide Navigarionbar using
NavigationPage.SetHasNavigationBar (this, false);
Check following link may be it's help you. and i think it's for your requirement.
http://blog.xhackers.co/xamarin-forms-contentpage-with-searchbar-in-the-navigation-bar/
Placing a SearchBar in the top/navigation bar
How to include view in NavigationBar of Xamarin Forms?
install or update Android support repository, google play service and Google USB driver
if you'r using shell app you can use Shell.TitleView instead of Navigation.TitleView as the following :
<Shell.TitleView>
<SearchBar x:Name="search" Margin="10,10,10,10"
HorizontalOptions="FillAndExpand"/>
</Shell.TitleView>