Event handler ordering in Xamarin - xamarin

I have a list view that I am popping up in Xamarin forms, that I want to hide if someone taps outside of the box. I have a tap gesture recognizer on the parent layout for the list view that handles that. In Android, it all works good. If I click off, it closes, but if I click on an element in the list view, it properly selects it. In iOS, the opposite happens. The gesture handler on the layout fires first and closes the list view without properly selecting the item.
So my question, is there a way to change the order on how the events are fired? If not, is there a better alternative to how I'm trying to accomplish this? Thanks!

If you are using ListView.ItemSelected or ListView.ItemTapped then I ran into the exact same issue the other day. The fix for me was to not use either of those and instead attach a TapGestureRecognizer to the ViewCell that is within the ListView. I also added an IsSelected property to the object that the ViewCell is being bound to so that I could change the background color of the item once it has been clicked.
public class SomePage : ContentPage {
private SomeModel _selectedModel; //It would be best to put this into your ViewModel
...
public SomePage() {
ListView list = new ListView {
ItemTemplate = new DataTemplate(() => {
ViewCell cell = new ViewCell {
View = new ContentView()
};
cell.View.GestureRecognizers.Add(new TapGestureRecognizer {
Command = new Command(() => {
if(_selectedModel != null) { _selectedModel.IsSelected = false; }
SomeModel model = (SomeModel)cell.BindingContext;
model.IsSelected = true;
_selectedModel = model;
})
}
return cell;
}
}
}
}

Related

Will it be a problem to have a TapGesture added inside of a data template in Xamarin? Should I somehow remove the event I added?

Within my DataTemplate (written in C#), I have this code:
var plusMinusGrid = new Grid
{
Children =
{
_minusFrame.Column(0).Bind(IsVisibleProperty, nameof(DeckRow.FRMIsVisible), source: this),
_plusFrame.Column(0).Bind(IsVisibleProperty, nameof(DeckRow.FRPIsVisible), source: this)
},
};
var plusMinusTapGesture = new TapGestureRecognizer();
plusMinusTapGesture.Tapped += PlusMinusTap;
plusMinusGrid.GestureRecognizers.Add(plusMinusTapGesture);
So I am adding the tap event to a part of each row.
My question is, will this be an issue as a memory leak and if that's the case is there a way that I can deal with this.
Here is what I have. Override the Disappearing method add a call to a CleanUp() that you write yourself. As I am doing the += on in the view model I add the -= there also. This is annoying as I also found that I needed to set itemsource to null, but itemsource is in the view. Since Disappearing is part of the view, I call the VM's CleanUp() method!
As my page is used modally this works fine. If your page is not modal, and you refresh the grid, make sure you do the -= on existing items before you repopulate.
View page :
public void CleanUp()
{
this.athleteDetailVM.CleanUp();
this.collectionV.ItemsSource = null;
}
VM Implementation:
public void CleanUp()
{
foreach (CheckedItem<EventResult> item in eventResults)
{
item.PropertyChanged -= null;
}
}

Xamarin Forms iOS TitleBarTextColor not changing

To change the TitleBarTextColor so far I tried a lot and my code now does change the back button color and the area on the very top of the screen, but the title!
in my AppDelegate FinishedLaunching function (it's after Forms.Init() and before LoadApplication()):
UINavigationBar.Appearance.SetTitleTextAttributes(new UITextAttributes
{
TextColor = UIColor.White
});
In my ViewModel:
(App.Current.MainPage as NavigationPage).BarBackgroundColor = Color.FromHex("#990000");
(App.Current.MainPage as NavigationPage).BarTextColor = Color.White;
And this is how I'm navigating between the pages (not all the pages):
await _navigationService.NavigateAsync(new Uri("http://wwww.x.com/NavigationPage/TabbedNavigationPage?selectedTab=XPage/Document", UriKind.Absolute));
I even try to call the ViewModel code after the Prism navigation but it doesn't work... I'm a beginner and don't fully comprehend Prism and or Xamarin Forms.
[EDIT] -> I also tried to create a new class and inherit it from NavigationPage, set the BarTextColor in its constructor and use that class in the navigation like this: await _navigationService.NavigateAsync(new Uri("http://wwww.x.com/NEWCLASSCREATED/TabbedNavigationPage?selectedTab=XPage/Document", UriKind.Absolute)); But, as you may know, it is still not working.
Here's a Image ;)
imageToSeeThatImNotLying
Thank you for your support!
So I finnaly managed to work this out...
What I had to do was to create a custom Content Page because all the other solutions wasn't working. So I created this custom renderer only in my iOS project:
[assembly: ExportRenderer(typeof(ContentPage), typeof(CustomContentPageRenderer))]
namespace TestProject.iOS.Bll.Utils.Renderers
{
public class CustomContentPageRenderer : PageRenderer
{
public override void DidMoveToParentViewController(UIViewController parent)
{
base.WillMoveToParentViewController(parent);
var titleView = new UITextView();
var page = this.Element as ContentPage;
try
{
if (!string.IsNullOrEmpty(page.Title))
{
titleView.Text = page.Title;
titleView.TextColor = UIColor.White;
titleView.Font = UIFont.SystemFontOfSize(17, UIFontWeight.Regular);
var bgColor = page.BackgroundColor;
titleView.BackgroundColor = UIColor.FromRGBA((int)bgColor.R, (int)bgColor.G, (int)bgColor.B, 0);
parent.NavigationItem.TitleView = titleView;
parent.NavigationItem.TitleView.ContentMode = UIViewContentMode.ScaleAspectFit;
}
}
catch (Exception e)
{
}
}
}
}
And I also removed all the code that I puted before in my AppDelegate file and in the App.xaml.cs file as well. I left the codes from the ViewModels because it was changing the back button to white, and I deleted the new NagivationPage class that I created before.
I'm going to explain why I did some of the things that you saw there:
To change the Title I created a UITextView() and set it to my NavigationItem.TitleView of the parent page. I set titleView.Text = page.Title; because my original page already have a title, so I'm just reusing it. And the backgroundcolor I had to do all of that so the backgroundcolor property works just in the way that I wanted.
And this DidMoveToParentViewController function was just so it can do all that before NavigationAsync from Prism.

How to hide navigation Toolbar icon in xamarin?

I want to hide navigation bar button in xamarin. how can i do that using binding. Toolbar item doesn't have "IsVisible" property.
Following is my xaml code
please help me to sort out this issue.
I would suggest to build a bindable ToolBoxItem. That way you can control the visibility through a view model property.
An implementation could look like that:
public class BindableToolbarItem : ToolbarItem
{
public static readonly BindableProperty IsVisibleProperty = BindableProperty.Create(nameof(IsVisible), typeof(bool), typeof(BindableToolbarItem), true, BindingMode.TwoWay, propertyChanged: OnIsVisibleChanged);
public bool IsVisible
{
get => (bool)GetValue(IsVisibleProperty);
set => SetValue(IsVisibleProperty, value);
}
private static void OnIsVisibleChanged(BindableObject bindable, object oldvalue, object newvalue)
{
var item = bindable as BindableToolbarItem;
if (item == null || item.Parent == null)
return;
var toolbarItems = ((ContentPage)item.Parent).ToolbarItems;
if ((bool)newvalue && !toolbarItems.Contains(item))
{
Device.BeginInvokeOnMainThread(() => { toolbarItems.Add(item); });
}
else if (!(bool)newvalue && toolbarItems.Contains(item))
{
Device.BeginInvokeOnMainThread(() => { toolbarItems.Remove(item); });
}
}
}
As you have discovered yourself there is not IsVisible. So you will have to implement functionality like that yourself if you still want it.
Another way would be to handle it in the pages' code-behind and remove or add the toolbar item whenever needed.
Adding and removing is simple, just add and remove items to the ToolbarItems collection: ToolbarItems.RemoveAt(0); for instance will remove the first toolbar item.
Putting #Gerald answer in action, it would be done this way:
void Done_Clicked(System.Object sender, System.EventArgs e)
{
//Do somthing and hide the done item
ShowDoneToolbarItem(false, (ToolbarItem)sender);
}
void Entry_Focused(System.Object sender, Xamarin.Forms.FocusEventArgs e)
{
//Show the done item
ShowDoneToolbarItem(true);
}
void ShowDoneToolbarItem(bool show, ToolbarItem item = null)
{
if(show)
{
ToolbarItem done = new ToolbarItem();
done.Text = "Done";
done.Clicked += Done_Clicked;
ToolbarItems.Add(done);
}
else if(item != null)
{
ToolbarItems.Remove(item);
}
}
This is cleaner and works from the code behind.
Well we need the IsVisible property for the front end, as xamarin doesn't have it, you can use Device.RuntimePlatform to check in real time which device the application is running. Since my code is in .cs of the XAML file, we can use xaml .cs to insert items into the screen.I put if () to do the logic and check if my device is on which platform, because I don't want it to display in UWP a toolbar.
The code is in .cs of the XAML file:
public kingTest()
{
InitializeComponent();
if((Device.RuntimePlatform == "Android")||(Device.RuntimePlatform == "iOS"))
{
ToolbarItem toolbar = new ToolbarItem();
toolbar.IconImageSource = "ic_ToolBar.png";
this.ToolbarItems.Add(toolbar);
}
};
I've achieved this easily using overloaded constructors. Here's an example:
View (add the name property):
<ContentPage x:Name="ContentPage"
<!-- rest of the tag -->
/>
Code-behind (add the toolbar items):
public partial class ExamplePage : ContentPage
{
public ExamplePage()
{
InitializeComponent();
BindingContext = this;
var saveToolbarItem = new ToolbarItem { Text = "Save" };
saveToolbarItem.Clicked += YourMethodToBeRan;
ContentPage.ToolbarItems.Add(saveToolbarItem);
}
public ExamplePage(Object object)
{
InitializeComponent();
BindingContext = this;
var updateToolbarItem = new ToolbarItem { Text = "Update" };
updateToolbarItem.Clicked += YourMethodToBeRan;
var deleteToolbarItem = new ToolbarItem { Text = "Delete" };
deleteToolbarItem.Clicked += YourMethodToBeRan;
ContentPage.ToolbarItems.Add(updateToolbarItem);
ContentPage.ToolbarItems.Add(deleteToolbarItem);
}
// rest of the class
}
The above pseudocode will add the "Save" toolbar item when the class is instantiated with no parameter, or the "Update" and "Delete" when a parameter is provided.
This isn't as elegant as IsEnabled / IsVisible booleans but it's a step in the right direction. Following this train of thought, you could modify the children of your toolbar during runtime to "show" and "hide" by adding and removing them as children.
Good luck!
I don't know if #tequila slammer's solution fully worked on Xamarin, but for us it only kind of works in .Net Maui (the evolution of Xamarin) and binding the IsVisible property to a variable.
Once the BindableToolbarItem is removed from the ContentPage's list of ToolbarItems, it is disconnected from the object that IsVisible is bound to forever.
For example: We want to use this control to hide or show a ToolbarItem that navigates to the admin screen, if I log in as the administrator on app launch, the item is there...great. If I then log out and log in as a non-admin, the item is not there...perfect. If I then log out and log in as an admin, the item is not there (the propertyChanged: OnIsVisibleChanged never fired)...:-(.
Not a big deal for us, if you want admin access then stopping the app and starting the app to log in as the admin is not a big ask.
In the newest release with .Net 7 the workaround works never more !
The reason is because the toolbar item which revomed will destoyed !

Custom tab item

I need to add a custom tab item into my TabbedPage. That shouldn't be a page but an overlay view. It is "More" item for the bottom menu opening a more items menu over the currently shown page.
So far I found the following solution:
protected override void OnCurrentPageChanged()
{
base.OnCurrentPageChanged();
if (this.isInitialized)
{
if (CurrentPage.Title == "More")
{
CurrentPage = this.lastSelectedPage;
}
}
this.lastSelectedPage = CurrentPage;
}
It's enough to prevent opening the corresponding fake page. After this I need to show an overlay view and have no item how to do it from the tabbed page.
Another solution I'm working out now is to write a custom renderer for my tabbed page and manage all the custom work there. The question in this case is how to show my custom view over the existing content. I tried AddView (iOS) in the renderer but getting runtime exception.
public override void ItemSelected(UITabBar tabbar, UITabBarItem item)
{
base.ItemSelected(tabbar, item);
var view = new UILabel()
{
Text = "Test"
};
View.Add(view);
}

How do I override the Xamarin Forms TabbedPage item fonts for iOS?

Wanting to achieve a consistent look for my Xamarin Forms app, I need to know how to change the font for the tabbed page tab bar icons. Using UITabBarItem.Appearance as the iOS API would suggest does not appear to have any effect. What's necessary to do this?
U need to write a custom renderer like this one , take a clue from below code ! it has what u r seeking
[assembly: ExportRenderer(typeof(ExtendedTabbedPage), typeof(TabbedPageCustom))]
namespace App.iOS
{
public class TabbedPageCustom : TabbedRenderer
{
public TabbedPageCustom ()
{
TabBar.TintColor = UIKit.UIColor.White;
TabBar.BarTintColor = UIKit.UIColor.White;
TabBar.BackgroundColor = UIKit.UIColor.Red;
}
protected override void OnElementChanged (VisualElementChangedEventArgs e)
{
base.OnElementChanged (e);
// Set Text Font for unselected tab states
UITextAttributes normalTextAttributes = new UITextAttributes();
normalTextAttributes.Font = UIFont.FromName("ChalkboardSE-Light", 20.0F); // unselected
normalTextAttributes.TextColor = UIKit.UIColor.Blue;
UITabBarItem.Appearance.SetTitleTextAttributes(normalTextAttributes, UIControlState.Normal);
}
public override UIViewController SelectedViewController {
get {
UITextAttributes selectedTextAttributes = new UITextAttributes();
selectedTextAttributes.Font = UIFont.FromName("ChalkboardSE-Bold", 20.0F); // SELECTED
if (base.SelectedViewController != null)
{
base.SelectedViewController.TabBarItem.SetTitleTextAttributes(selectedTextAttributes, UIControlState.Normal);
}
return base.SelectedViewController;
}
set {
base.SelectedViewController = value;
foreach (UIViewController viewController in base.ViewControllers)
{
UITextAttributes normalTextAttributes = new UITextAttributes();
normalTextAttributes.Font = UIFont.FromName("ChalkboardSE-Light", 20.0F); // unselected
normalTextAttributes.TextColor = UIKit.UIColor.Blue;
viewController.TabBarItem.SetTitleTextAttributes(normalTextAttributes, UIControlState.Normal);
}
}
}
}
}
This was a particularly interesting problem. I tried:
UITabBarItem.Appearance
Using the UITabBarItem.Appearance.SetTitleTextAttributes method to update the UITextAttribute to my font (size 9.0f) for UIControlState.Normal. This didn't appear to make any difference.
UINavigationBar.Appearance
I found out that setting UINavigationBar.Appearance.SetTitleTextAttributes would update both the UINavigationBar text appearance as well as the UITabBarItem text appearance.
Which was a problem because the tabbed page item font size was far too large.
Customizing the TabbedRenderer
Inspired by a sample I saw somewhere, I subclassed TabbedRenderer in the iOS project.
I tried overriding the settor for TabbedRenderer.SelectedViewController property and loop through the ViewControllers property to set their items. The icons would display with the standard font, but once the user changed the tab they would all update to the desired font. Almost there!
I then tried overriding AddChildViewController and updating that controller's TabBarItem after it was added which ended up having no effect. The TabBarItem for the added page was being updated at some point after the controller was added.
Eventually I found out that overriding ViewWillAppear and setting the appearance for all the tab bar items at that time seemed to do the job I desired.
I've included a sample in this gist.

Resources