Skip to content

Instantly share code, notes, and snippets.

@programmation
Last active August 8, 2017 02:31
Show Gist options
  • Save programmation/80ec171c9fb60eb10a5dc0880244f288 to your computer and use it in GitHub Desktop.
Save programmation/80ec171c9fb60eb10a5dc0880244f288 to your computer and use it in GitHub Desktop.
// from https://forums.xamarin.com/discussion/comment/168974/#Comment_168974
public class BindableToolbarItem : ToolbarItem
{
public static readonly BindableProperty IsVisibleProperty =
BindableProperty.Create("IsVisible", typeof (bool), typeof (BindableToolbarItem),
true, BindingMode.TwoWay, propertyChanged: OnIsVisibleChanged);
public BindableToolbarItem()
{
//InitVisibility();
}
protected override void OnParentSet()
{
base.OnParentSet();
InitVisibility();
}
public bool IsVisible
{
get { return (bool) GetValue(IsVisibleProperty); }
set { SetValue(IsVisibleProperty, value); }
}
private void InitVisibility()
{
OnIsVisibleChanged(this, false, IsVisible);
}
private static void OnIsVisibleChanged(BindableObject bindable, object oldvalue, object newvalue)
{
var item = bindable as BindableToolbarItem;
if (item != null && item.Parent == null)
return;
if (item != null)
{
var items = ((ContentPage) item.Parent).ToolbarItems;
if ((bool) newvalue && !items.Contains(item))
{
Device.BeginInvokeOnMainThread(() => { items.Add(item); });
}
else if (!(bool) newvalue && items.Contains(item))
{
Device.BeginInvokeOnMainThread(() => { items.Remove(item); });
}
}
}
// Usage:
In your content pages attributes add this
xmlns:control="clr-namespace:Mobile.Controls"
#3. Add in your bindable toolbar items
<ContentPage.ToolbarItems>
<control:BindableToolbarItem Text="Delete" Icon="delete.png" Command="{Binding DeleteCommand}" IsVisible="{Binding IsVisible}" />
</ContentPage.ToolbarItems>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment