I am new to Xamarin. I have a listview which is bound to an ObservableCollection with data coming from sqlite.
List view has two labels. I want to hide one of the labels (lblGroup) when someone clicks on the toolbar menu button. This code is not working.
Here's the code:
<StackLayout>
<ListView x:Name="lstItems" HasUnevenRows="True" ItemSelected="lstItems_ItemSelected" >
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<StackLayout VerticalOptions="StartAndExpand" Padding="20, 5, 20, 5" Spacing="3">
<Label x:Name="lblItemName" IsVisible="{Binding IsNameVisible}" Text="{Binding ItemName}" ></Label>
<Label x:Name="lblGroup" IsVisible="{Binding IsGroupVisible}" Text="{Binding ItemGroup}" ></Label>
</StackLayout>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</StackLayout>
In xaml.cs file, I am binding ObservableCollection to my list view.
public ObservableCollection<Items> itemsObs;
public ItemDetails()
{
InitializeComponent();
LoadItems();
}
private async LoadItems()
{
List<Items> items = _con.QueryAsync<Items>(Queries.ItemsById(ItemsId));
itemsObs = new ObservableCollection<Items>(items);
lstItems.ItemsSource = itemsObs ;
}
private void menu_Clicked(object sender, EventArgs e)
{
itemsObs.ToList().ForEach(a => a.IsGroupVisible = false);
}
As Jason's reply, I guess that you don't implement INotifyPropertyChanged interface for IsGroupVisible property in Items class, please modify your Items class like this:
public class Items:ViewModelBase
{
private bool _IsNameVisible;
public bool IsNameVisible
{
get { return _IsNameVisible; }
set
{
_IsNameVisible = value;
RaisePropertyChanged("");
}
}
private bool _IsGroupVisible;
public bool IsGroupVisible
{
get
{ return _IsGroupVisible; }
set
{
_IsGroupVisible = value;
RaisePropertyChanged("IsGroupVisible");
}
}
public string ItemName { get; set; }
public string ItemGroup { get; set; }
}
The ViewModelBase class is implementing INotifyPropertychanged, to notify data changed.
public class ViewModelBase : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
public void RaisePropertyChanged(string propertyName)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
}
And you set lstItems.ItemsSource = itemsObs, but you change versesObs, what is versesObs, I think you should change itemsObs.