patterncsharpMinor
Changing visibility of ToolbarItem - Xamarin.Forms
Viewed 0 times
toolbaritemvisibilityxamarinchangingforms
Problem
I want to fill collection of
I implemented
```
public class CustomToolbarItem : ToolbarItem
{
public static readonly BindableProperty IsVisibleProperty =
BindableProperty.Create(nameof(IsVisible),
typeof(bool),
typeof(CustomToolbarItem),
ToolbarItems from XAML, but change visibility of some ToolbarItem from view model. I implemented
BasePage with some wrapper around ToolbarItems collection:public class BasePage : ContentPage
{
public IList CustomToolbar { get; private set; }
public BasePage()
{
var items = new ObservableCollection();
items.CollectionChanged += ToolbarItemsChanged;
CustomToolbar = items;
}
private void ToolbarItemsChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
{
ToolbarItems.Clear();
foreach (var item in CustomToolbar)
{
item.PropertyChanged += OnToolbarItemPropertyChanged;
if (item.IsVisible)
{
ToolbarItems.Add(item);
}
}
}
private void OnToolbarItemPropertyChanged(object sender, PropertyChangedEventArgs e)
{
if (e.PropertyName == CustomToolbarItem.IsVisibleProperty.PropertyName)
{
UpdateToolbar();
}
}
private void UpdateToolbar()
{
foreach (var item in CustomToolbar)
{
if (item.IsVisible)
{
ToolbarItems.Add(item);
}
else
{
ToolbarItems.Remove(item);
}
}
}
protected override void OnDisappearing()
{
base.OnDisappearing();
ToolbarItems.Clear();
CustomToolbar.Clear();
foreach (var item in CustomToolbar)
{
item.PropertyChanged -= OnToolbarItemPropertyChanged;
}
}
}CustomToolbarItem.cs:```
public class CustomToolbarItem : ToolbarItem
{
public static readonly BindableProperty IsVisibleProperty =
BindableProperty.Create(nameof(IsVisible),
typeof(bool),
typeof(CustomToolbarItem),
Solution
Two things:
-
You clear
-
Handlers
-
You clear
ToolbarItems and CustomToolbar when page dissapearing, this causes problem: when you show next page and then go back, you won't see your items anymore, because they were cleared.-
Handlers
OnToolbarItemPropertyChanged will not be removed in foreach cycle, because you clear list before this cycle.Context
StackExchange Code Review Q#135481, answer score: 3
Revisions (0)
No revisions yet.