Metro App OnNavigatedTo setting textbox value in a different method - windows

I am following around on a kindle book I bought for developing metro apps. For some reason I cannot set the text value of a text box in a method outside the OnNavigatedTo method. This is the code that the book provides:
protected override void OnNavigatedTo(NavigationEventArgs e)
{
//passed in the view model
viewModel = e.Parameter as ViewModel;
this.DataContext = viewModel;
viewModel.PropertyChanged += (sender, eventArgs) =>
{
if (eventArgs.PropertyName == "SelectedItemIndex")
{
if (viewModel.SelectedIndex == -1)
{
SetItemDetail(null);
}
else
{
SetItemDetail(viewModel.GroceryList[viewModel.SelectedIndex]);
}
}
SetItemDetail(viewModel.GroceryList[viewModel.SelectedIndex]);
};
}
private void SetItemDetail(GroceryItem item)
{
ItemDetailName.Text = "test"; //(item == null) ? "" : item.Name;
ItemDetailQuantity.Text = "test"; //(item == null) ? "" : item.Quantity.ToString();
//if (item != null)
//{
// ItemDetailStore.SelectedItem = item.Store;
//}
//else
//{
// ItemDetailStore.SelectedIndex = -1;
//}
}
I have commented parts out in the set item detail method, but I still cannot set the value of a textbox when I click it (this is supposed to be the behavior). I have used break points and the property of the textbox is getting set, however, it is not displayed on screen.
Thanks.

Related

How to implement TabLayout.IOnTabSelectedListener.OnTabUnselected with TabbedPage.ToolbarPlacement="Bottom" - Xamarin Forms?

I just recently used android:TabbedPage.ToolbarPlacement="Bottom". I used to have the following code:
void TabLayout.IOnTabSelectedListener.OnTabUnselected(TabLayout.Tab tab)
{
var playPage = Element.CurrentPage as NavigationPage;
if (!(playPage.RootPage is PhrasesFrame))
return;
var tabLayout = (TabLayout)ViewGroup.GetChildAt(1);
var playTab = tabLayout.GetTabAt(4);
tab.SetText("Play");
tab.SetIcon(Resource.Drawable.ionicons_2_0_1_play_outline_25);
App.pauseCard = true;
}
Anyone knows how can I implement this with ToolbarPlacement="Bottom" ? I have implemented both BottomNavigationView.IOnNavigationItemSelectedListener, BottomNavigationView.IOnNavigationItemReselectedListener but can't find any reference for UnselectedTab if there is any.
Edit:
Previous custom renderer using the default tab position and implementing TabLayout:
namespace Japanese.Droid
{
public class MyTabbedPageRenderer: TabbedPageRenderer, TabLayout.IOnTabSelectedListener
{
ViewPager viewPager;
TabLayout tabLayout;
bool setup;
public MyTabbedPageRenderer(Context context): base(context){ }
protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e)
{
// More codes here
}
void TabLayout.IOnTabSelectedListener.OnTabReselected(TabLayout.Tab tab)
{
UpdateTab(tab);
}
void TabLayout.IOnTabSelectedListener.OnTabSelected(TabLayout.Tab tab)
{
UpdateTab(tab);
}
void TabLayout.IOnTabSelectedListener.OnTabUnselected(TabLayout.Tab tab)
{
var playPage = Element.CurrentPage as NavigationPage;
if (!(playPage.RootPage is PhrasesFrame))
return;
var tabLayout = (TabLayout)ViewGroup.GetChildAt(1);
var playTab = tabLayout.GetTabAt(4);
tab.SetText("Play");
tab.SetIcon(Resource.Drawable.ionicons_2_0_1_play_outline_25);
App.pauseCard = true;
}
void UpdateTab(TabLayout.Tab tab)
{
// To have the logic only on he tab on position 1
if (tab == null || tab.Position != 4)
{
return;
}
if (tab.Text == "Play")
{
tab.SetText("Pause");
tab.SetIcon(Resource.Drawable.ionicons_2_0_1_pause_outline_22);
App.pauseCard = false;
}
else
{
tab.SetText("Play");
tab.SetIcon(Resource.Drawable.ionicons_2_0_1_play_outline_25);
App.pauseCard = true;
}
}
}
}
Current custom renderer using the ToolbarPlacement="Bottom":
namespace Japanese.Droid
{
public class BottomTabPageRenderer : TabbedPageRenderer, BottomNavigationView.IOnNavigationItemSelectedListener, BottomNavigationView.IOnNavigationItemReselectedListener
{
public BottomTabPageRenderer(Context context) : base(context) { }
protected override void OnElementChanged(ElementChangedEventArgs<TabbedPage> e)
{
base.OnElementChanged(e);
// More codes here
}
bool BottomNavigationView.IOnNavigationItemSelectedListener.OnNavigationItemSelected(IMenuItem item)
{
base.OnNavigationItemSelected(item);
UpdateTab(item)
}
void BottomNavigationView.IOnNavigationItemReselectedListener.OnNavigationItemReselected(IMenuItem item)
{
UpdateTab(item);
}
void UpdateTab(IMenuItem item)
{
var playTabId = 4;
var title = item.TitleFormatted.ToString();
if (item == null || item.ItemId != playTabId)
{
return;
}
if (item.ItemId == playTabId)
{
if (title == "Play")
{
item.SetTitle("Pause");
item.SetIcon(Resource.Drawable.ionicons_2_0_1_pause_outline_22);
App.pauseCard = false;
}
else
{
item.SetTitle("Play");
item.SetIcon(Resource.Drawable.ionicons_2_0_1_play_outline_25);
App.pauseCard = true;
}
}
}
}
}
So now my problem is I don't have any idea how will I implement the TabLayout.IOnTabSelectedListener.OnTabUnselected in the new custom renderer.
There is no official stuff for OnTabReselected event for TabbedPage's bottom navigation or
BottomNavigationView because It doesn't use TabLayout.Tab for a start. Many overridden methods of TabbedPageRenderer not being called like SetTabIcon. If you are using IOnTabSelectedListener interface(As your first part of code) you have three methods to use.
void OnTabReselected(Tab tab);
void OnTabSelected(Tab tab);
void OnTabUnselected(Tab tab);
But when it comes to BottomNavigationView interface you have only two methods
void OnNavigationItemReselected
bool OnNavigationItemSelected
So we don't have built in OnTabUnselected method. Here you need to write custom code to make unseleted event.
I have tried this code without using custom renderer using 4 tabs pages & the xaml of tabbed written in MailPage.xaml file. First declare List<string> in App.xaml.cs file to store Title of all tabs
public static List<string> Titles {get;set;}
Add tabs pages title in above list from MainPage.xaml.cs file's OnAppearing method
protected override void OnAppearing()
{
for (int i = 0; i < this.Children.Count; i++)
{
App.Titles.Add(this.Children[i].Title);
}
}
Now go to your MyTabbedPage class in which is available in shared project.
public class MyTabbedPage : Xamarin.Forms.TabbedPage
{
string selectedTab = string.Empty;
string unSelectedTab = string.Empty;
bool isValid;
public MyTabbedPage()
{
On<Xamarin.Forms.PlatformConfiguration.Android>().SetToolbarPlacement(ToolbarPlacement.Bottom);
this.CurrentPageChanged += delegate
{
unSelectedTab = selectedTab;
selectedTab = CurrentPage.Title;
if (App.Titles != null)
isValid = true;
else
App.Titles = new List<string>();
if (isValid)
{
MoveTitles(selectedTab);
//Pass 0 index for tab selected & 1 for tab unselected
var unSelecteTabTitle = App.Titles[1];
//TabEvents(1); here you know which tab unseleted call any method
}
};
}
//This method is for to moving selected title on top of App.Titles list & unseleted tab title automatic shifts at index 1
void MoveTitles(string selected)
{
var holdTitles = App.Titles;
if (holdTitles.Count > 0)
{
int indexSel = holdTitles.FindIndex(x => x.StartsWith(selected));
holdTitles.RemoveAt(indexSel);
holdTitles.Insert(0, selected);
}
App.Titles = holdTitles;
}
}
Or you can make swith case like this
void TabEvents(int index)
{
switch (index)
{
case 0:
//Tab selected
break;
case 1:
//Tab unselected
break;
}
}
Few things I should mention that MainPage.xaml.cs file inheriting MyTabbedPage
public partial class MainPage : MyTabbedPage
Structure of MainPage.xaml file
<?xml version="1.0" encoding="utf-8" ?>
<local:MyTabbedPage
<TabbedPage.Children>
<NavigationPage Title="Browse">
</NavigationPage>
</TabbedPage.Children>
</local:MyTabbedPage>
Answer seems long but hope it help you.
As per G.Hakim's suggestion, I was able to do what I wanted to do by capturing the tab item I wanted to work on and do the necessary actions in BottomNavigationView.IOnNavigationItemSelectedListener.OnNavigationItemSelected.
namespace Japanese.Droid
{
public class BottomTabPageRenderer : TabbedPageRenderer, BottomNavigationView.IOnNavigationItemSelectedListener, BottomNavigationView.IOnNavigationItemReselectedListener
{
// same as above
bool BottomNavigationView.IOnNavigationItemSelectedListener.OnNavigationItemSelected(IMenuItem item)
{
base.OnNavigationItemSelected(item);
if(item.ItemId == 4 && item.TitleFormatted.ToString() == "Play")
{
item.SetTitle("Pause");
item.SetIcon(Resource.Drawable.ionicons_2_0_1_pause_outline_22);
App.pauseCard = false;
playTab = item;
}
if(item.ItemId !=4 && playTab.TitleFormatted.ToString() == "Pause")
{
playTab.SetTitle("Play");
playTab.SetIcon(Resource.Drawable.ionicons_2_0_1_play_outline_25);
App.pauseCard = true;
}
return true;
}
// same as above
}
}

How to update tabbar badge-icon in Xamarin.Forms.iOS?

I can successfully work with the badge on my tabbar if i use it straight in my ViewWillAppear function but if i create a function where i try to control it then the badge does not appear.
This is the tabbedpaged renderer where I have to the function that changes the badge.
public override void ViewWillAppear(bool animated)
{
if (TabBar == null) return;
if (TabBar.Items == null) return;
var tabs = Element as TabbedPage;
if (tabs != null)
{
for (int i = 0; i < TabBar.Items.Length; i++)
{
UpdateItem(TabBar.Items[i], tabs.Children[i].Icon);
}
}
base.ViewWillAppear(animated);
}
private void UpdateItem(UITabBarItem item, string icon)
{
TabBar.UnselectedItemTintColor = UIColor.White;
}
public void UpdateBadge ()
{
var tabs = Element as TabbedPage;
if (tabs != null)
{
Device.BeginInvokeOnMainThread(() =>
{
var tab = TabBar.Items[3];
tab.BadgeValue = "New";
tab.BadgeColor = UIColor.Red;
});
}
}
Then I have another file where I handle a pushnotification and this is where I call the UpdateBadgefunction to both push a notification and also update the badge in the app.
void IPush.SendPush()
{
var notification = new UILocalNotification();
notification.SoundName = UILocalNotification.DefaultSoundName;
UIApplication.SharedApplication.PresentLocalNotificationNow(notification);
TabbedPage_Renderer tpr = new TabbedPage_Renderer();
tpr.UpdateBadge();
}
But as stated above this does not add the badge.
If I however add...
var tab = TabBar.Items[3];
tab.BadgeValue = "New";
tab.BadgeColor = UIColor.Red;
...inside the ViewWillAppear straight away it successfully shows an iconbadge when i start the app up but the idea is to control it so i can update the badge whenever i want.
We should not use the instance of the Renderer directly.
If you want to change the UI in the platform's renderer, we can try to define a BindableProperty in the forms. Then tell the renderer do some configuration when this property changed.
Firstly, define a BindableProperty in the page which you want to change its Badge like:
public static readonly BindableProperty BadgeTextProperty = BindableProperty.Create(nameof(BadgeText), typeof(string), typeof(MainPage), "0");
public string BadgeText {
set
{
SetValue(BadgeTextProperty, value);
}
get
{
return (string)GetValue(BadgeTextProperty);
}
}
Secondly, in the renderer, we can set the badge text when this property changed like:
for (int i = 0; i < TabBar.Items.Length; i++)
{
UpdateItem(TabBar.Items[i], tabs.Children[i].Icon);
//register the property changed event
tabs.Children[i].PropertyChanged += TabbarPageRenderer_PropertyChanged;
}
private void TabbarPageRenderer_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
{
var page = sender as Page;
if (page == null)
return;
if (e.PropertyName == "BadgeText")
{
if (CheckValidTabIndex(page, out int tabIndex))
{
switch(tabIndex)
{
case 0:
UpdateBadge(TabBar.Items[tabIndex], (page as MainPage).BadgeText);
break;
case 1:
//Second Page, you can expand this switch depending on your tabs children
UpdateBadge(TabBar.Items[tabIndex], (page as SecondPage).BadgeText);
break;
default:
break;
}
}
return;
}
}
public bool CheckValidTabIndex(Page page, out int tabIndex)
{
tabIndex = Tabbed.Children.IndexOf(page);
return tabIndex < TabBar.Items.Length;
}
private void UpdateItem(UITabBarItem item, string icon)
{
TabBar.UnselectedItemTintColor = UIColor.White;
...//set the tabItem
}
private void UpdateBadge(UITabBarItem item, string badgeText)
{
item.BadgeValue = text;
item.BadgeColor = UIColor.Red;
}
At last, set the BadgeText in the forms when you want to update the badge.

How to change Picker Border color in xamarin forms

My borderless custom renderer for picker
public class BorderlessPickerRenderer : PickerRenderer
{
public static void Init() { }
protected override void OnElementChanged(ElementChangedEventArgs<Picker> e)
{
base.OnElementChanged(e);
if (e.OldElement == null)
{
Control.Background = null;
}
}
}
It will change the picker list text color as white. please see the screenshot
If you check the source code of PickerRenderer, you will find that the Dialog is totally generated in the code behind.
So here to set a Transparent(border-less) background, we can re-write the Click event of this control, for example:
public class BorderlessPickerRenderer : Xamarin.Forms.Platform.Android.PickerRenderer
{
private IElementController ElementController => Element as IElementController;
private AlertDialog _dialog;
protected override void OnElementChanged(ElementChangedEventArgs<Picker> e)
{
base.OnElementChanged(e);
if (e.NewElement == null || e.OldElement != null)
return;
Control.Click += Control_Click;
}
protected override void Dispose(bool disposing)
{
Control.Click -= Control_Click;
base.Dispose(disposing);
}
private void Control_Click(object sender, EventArgs e)
{
Picker model = Element;
var picker = new NumberPicker(Context);
if (model.Items != null && model.Items.Any())
{
picker.MaxValue = model.Items.Count - 1;
picker.MinValue = 0;
picker.SetDisplayedValues(model.Items.ToArray());
picker.WrapSelectorWheel = false;
picker.DescendantFocusability = DescendantFocusability.BlockDescendants;
picker.Value = model.SelectedIndex;
}
var layout = new LinearLayout(Context) { Orientation = Orientation.Vertical };
layout.AddView(picker);
ElementController.SetValueFromRenderer(VisualElement.IsFocusedPropertyKey, true);
var builder = new AlertDialog.Builder(Context);
builder.SetView(layout);
builder.SetTitle(model.Title ?? "");
builder.SetNegativeButton(global::Android.Resource.String.Cancel, (s, a) =>
{
ElementController.SetValueFromRenderer(VisualElement.IsFocusedPropertyKey, false);
// It is possible for the Content of the Page to be changed when Focus is changed.
// In this case, we'll lose our Control.
Control?.ClearFocus();
_dialog = null;
});
builder.SetPositiveButton(global::Android.Resource.String.Ok, (s, a) =>
{
ElementController.SetValueFromRenderer(Picker.SelectedIndexProperty, picker.Value);
// It is possible for the Content of the Page to be changed on SelectedIndexChanged.
// In this case, the Element & Control will no longer exist.
if (Element != null)
{
if (model.Items.Count > 0 && Element.SelectedIndex >= 0)
Control.Text = model.Items[Element.SelectedIndex];
ElementController.SetValueFromRenderer(VisualElement.IsFocusedPropertyKey, false);
// It is also possible for the Content of the Page to be changed when Focus is changed.
// In this case, we'll lose our Control.
Control?.ClearFocus();
}
_dialog = null;
});
_dialog = builder.Create();
_dialog.DismissEvent += (ssender, args) =>
{
ElementController?.SetValueFromRenderer(VisualElement.IsFocusedPropertyKey, false);
};
_dialog.Show();
_dialog.Window.SetBackgroundDrawable(new ColorDrawable(Android.Graphics.Color.Transparent));
}
}
Rendering image of this custom picker:
The font color and button's style can be modified as you need since you created this dialog by yourself. And the style of the dialog also depends on the style of your app.

[Xamarin.Forms][Android] Change back and next color in navigation

I' have some navigation page and I want to override the color for the back button and my next button ( ToolbarItem )
I Already tried BarTextColor property but it change color for all navigation header text.
It's done in IOS, but I' not able to find a solution for android.
It works perfectly for the title but not for the Icons.
Here my code :
protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e)
{
base.OnElementPropertyChanged(sender, e);
var page = this.Element as NavigationPage;
if (page != null && toolbar != null)
{
toolbar.SetTitleTextColor(Color.Black.ToAndroid());
if (toolbar.NavigationIcon != null)
toolbar.NavigationIcon.SetColorFilter(Color.Green.ToAndroid(), Android.Graphics.PorterDuff.Mode.Multiply);
if (toolbar.OverflowIcon != null)
toolbar.OverflowIcon.SetColorFilter(Color.Green.ToAndroid(), Android.Graphics.PorterDuff.Mode.Multiply);
}
}
I' have some navigation page and I want to override the color for the back button and my next button ( ToolbarItem )
Your next button is a ToolbarItem, which is defined by yourself. So it won't be a problem for you to customize it. The difficult part lies in the back button, because it is offered by Xamarin.Forms. You need to override the NavigationPageRenderer to change the color:
public class MyNavigationPageRenderer : NavigationPageRenderer
{
protected override void OnElementChanged(ElementChangedEventArgs<NavigationPage> e)
{
base.OnElementChanged(e);
if (e.NewElement != null)
{
var navController = (INavigationPageController)e.NewElement;
navController.PushRequested += NavController_PushRequested;
navController.PopRequested += NavController_PopRequested;
}
}
private void NavController_PopRequested(object sender, Xamarin.Forms.Internals.NavigationRequestedEventArgs e)
{
Device.StartTimer(TimeSpan.FromMilliseconds(220), () =>
{
ChangeIconColor();
return false;
});
}
private void NavController_PushRequested(object sender, Xamarin.Forms.Internals.NavigationRequestedEventArgs e)
{
ChangeIconColor();
}
private void ChangeIconColor()
{
int count = this.ViewGroup.ChildCount;
var toolbar = GetToolbar();
if (toolbar.NavigationIcon != null)
{
var drawable = (toolbar.NavigationIcon as DrawerArrowDrawable);
drawable.Color = Resource.Color.material_grey_850;//set the navigation icon color here
}
}
private AToolbar GetToolbar()
{
for (int i = 0; i < this.ViewGroup.ChildCount; i++)
{
var child = this.ViewGroup.GetChildAt(i);
if (child is AToolbar)
{
return (AToolbar)child;
}
}
return null;
}
}
A little explanation to the codes above: PushRequest and PopRequest fires when you push and pop a new page to the navigation page and it is the perfect time for you to customize the existing Toolbar's NavigationIcon. So first find the Toolbar using GetToolbar then change the icon color by ChangeIconColor.

How to display Pin's Label (on a Map) without clicking on Xamarin.Forms

How can I make the pin to display label by default (without clicking it) when it is added to the map in Xamarin.Forms.
map.MoveToRegion(MapSpan.FromCenterAndRadius(position, Distance.FromMiles(0.4)));
var pin = new Pin
{
Type = PinType.Place,
Position = position,
Label = "Some Text",
};
map.Pins.Add(pin);
You can do it via a custom map render.
As an example, on iOS you can add two delegates to the MKMapView control:
DidAddAnnotationViews: Any time a MKAnnotation is added, pre-select them all..
DidDeselectAnnotationView: If someone/something tries to deselect the MKAnnotation, just re-select them all...
Working Example as a starting point:
[assembly: ExportRenderer(typeof(PinViewMap), typeof(PinViewMapRenderer))]
namespace WorkingWithMaps.iOS
{
public class PinViewMapRenderer : MapRenderer
{
protected override void OnElementChanged(ElementChangedEventArgs<Xamarin.Forms.View> e)
{
base.OnElementChanged(e);
if (Control != null)
{
var map = Control as MKMapView;
map.DidDeselectAnnotationView += (object sender, MKAnnotationViewEventArgs eventArgs) =>
{
foreach (var anno in ((MKMapView)sender).Annotations)
{
((MKMapView)sender).SelectAnnotation(anno, true);
}
};
map.DidAddAnnotationViews += (object sender, MKMapViewAnnotationEventArgs eventArgs) =>
{
foreach (var anno in ((MKMapView)sender).Annotations)
{
((MKMapView)sender).SelectAnnotation(anno, true);
}
};
}
}
}
}

Resources