如何将字典绑定到Listview ItemSource

时间:2019-08-07 09:18:04

标签: forms xamarin nullreferenceexception

我有一个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];
        }
    }

2 个答案:

答案 0 :(得分:0)

如果ItemSource是字典,则只需绑定“键”和“值”即可。我想那是你所做的。但是您无需创建属性“键”和“值”。所以请删除它。

//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}",则可以像以前一样绑定键和值(提供的YourDictionary类型为Dictionary<string,string>)。

答案 1 :(得分:0)

由于不知道源数据的类型,如果源数据是来自Web api的json类型,则可以参考此discussion将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>