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

时间:2020-04-06 23:43:57

标签: listview xamarin observablecollection

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

列表视图有两个标签。当某人单击工具栏菜单按钮时,我想隐藏标签之一(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);
}

1 个答案:

答案 0 :(得分:1)

作为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,但是您更改了versesObs,什么是versesObs,我认为您应该更改itemsObs。

相关问题