在列表视图中切换标签的可见性



我是Xamarin的新手。我有一个列表视图,它绑定到一个ObservableCollection,数据来自sqlite。

列表视图有两个标签。当有人单击工具栏菜单按钮时,我想隐藏其中一个标签(lblGroup(。此代码不起作用。

这是代码:

<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>

在xaml.cs文件中,我将ObservableCollection绑定到我的列表视图。

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);
}

作为Jason的回复,我猜您没有在Items类中为IsGroupVisible属性实现INotifyPropertyChanged接口,请这样修改您的Items类:

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; }
}

ViewModelBase类正在实现INotifyPropertychanged,以通知数据已更改。

public class ViewModelBase : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;

public void RaisePropertyChanged(string propertyName)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
}

你设置了lstItems.ItemsSource=itemsObs,但你更改了verseObs,什么是verseObS,我认为你应该更改itemsOb。

最新更新