如何将字典绑定到 Listview itemssource

how to bind dictionary to Listview itemsource

我有一个 ListView 如下所示。 我如何将字典绑定到 ListView Itemsource 以便我作为键的标签和 ENtry 具有价值?

我不知道如何进行下一步

我试过这个但是我得到 空引用异常

<ListView x:Name="ItemsListView" VerticalOptions="FillAndExpand" SeparatorVisibility="None" HasUnevenRows="true" ItemsSource="{Binding dictionary}">
  <ListView.ItemTemplate>
    <DataTemplate>
      <ViewCell>
        <Grid>
          <Label Text="{Binding Key}" Grid.Row="1" Grid.Column="0" Style="{DynamicResource lblTitle}" />
          <Entry x:Name="test" Text="{Binding Value}" Grid.Row="1" Grid.Column="1" />
        </Grid>

      </ViewCell>

    </DataTemplate>
  </ListView.ItemTemplate>
</ListView>

查看模型

public List<string> Key
{
    get { return key; }
    set
    {
        SetProperty(ref key, value);

    }
}

public List<Int32> Value
{
    get { return val; }
    set
    {
        SetProperty(ref val, value);
    }
}**

for (int i = 0; i < AllProductsList.Count; i++)
{
    Value.Add(0);
    //Value = new ObservableCollection<Int32>(val);
}

for (int j = 0; j < AllProductsList.Count; j++)
{
    for (int k = 0; k < Value.Count; k++)
    {
        if (j == k)
        {
            dictionary[Key[j]] = Value[k];
        }
    }

如果 ItemSource 是字典,则只需绑定 "Key" 和 "Value" 即可。我想这就是你所做的。但是您不需要创建属性 "Key" 和 "Value"。所以请删除那个..

//Remove these Properties
    public List<string> Key
            {
                get { return key; }
                set
                {
                    SetProperty(ref key, value);

                }
            }
            public List<Int32> Value
            {
                get { return val; }
                set
                {
                    SetProperty(ref val, value);

                }
            }**

您在 Xaml 中所做的是正确的。

<Grid>
      <Label Text="{Binding Key}" Grid.Row="1" Grid.Column="0" Style="{DynamicResource lblTitle}" />
      <Entry x:Name="test" Text="{Binding Value}" Grid.Row="1" Grid.Column="1" />
    </Grid>

标签将显示键,条目将显示值。现在,让你的列表的 ItemSource 绑定你的字典(而不是 IList/List)。 如果你设置了ItemSource= "{Binding YourDictionary}",那么你可以像你一样绑定Key和Value(前提是YourDictionary的类型是Dictionary<string,string>)。

因为不知道你的源数据是什么类型,如果源数据是来自网络的json类型api,你可以参考这个转换json 反对 ViewMidel。

在ListView中,ItemSource可以如下使用:

DictionaryModel.cs:

public class DictionaryModel : INotifyPropertyChanged
{
    string key= string.Empty;
    public string Key
    {
        get { return key; }
        set { SetProperty(ref key, value); }
    }

    Int32 valueint = 0;
    public Int32 Value
    {
        get { return valueint; }
        set { SetProperty(ref valueint, value); }
    }

     protected bool SetProperty<T>(ref T backingStore, T value,
        [CallerMemberName]string propertyName = "",
        Action onChanged = null)
    {
        if (EqualityComparer<T>.Default.Equals(backingStore, value))
            return false;

        backingStore = value;
        onChanged?.Invoke();
        OnPropertyChanged(propertyName);
        return true;
    }

    #region INotifyPropertyChanged
    public event PropertyChangedEventHandler PropertyChanged;
    protected void OnPropertyChanged([CallerMemberName] string propertyName = "")
    {
        var changed = PropertyChanged;
        if (changed == null)
            return;

        changed.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
    #endregion
}

ViewModel.cs:

public class ViewModel
{

   public IList<DictionaryModel> DictionaryModels { get; private set; }

   public ViewModel()
   {
      DictionaryModels = new List<DictionaryModel>();

      // set demo data 
      DictionaryModels.Add(new DictionaryModel
      {
           Key = "Baboon",
           Value= 1,
      });

      DictionaryModels.Add(new DictionaryModel
      {
           Key = "Capuchin",
           Value= 2,
      });

   }

}

然后在 ContenPage.cs 中,绑定 ViewModel:

BindingContext = new ViewModel();

终于在 Xaml :

<ListView x:Name="ItemsListView" VerticalOptions="FillAndExpand" SeparatorVisibility="None" HasUnevenRows="true" ItemsSource="{Binding DictionaryModels}">
  <ListView.ItemTemplate>
    <DataTemplate>
      <ViewCell>
        <Grid>
          <Label Text="{Binding Key}" Grid.Row="1" Grid.Column="0" Style="{DynamicResource lblTitle}" />
          <Entry x:Name="test" Text="{Binding Value}" Grid.Row="1" Grid.Column="1" />
        </Grid>

      </ViewCell>

    </DataTemplate>
  </ListView.ItemTemplate>
</ListView>