【问题标题】:how to bind dictionary to Listview itemsource如何将字典绑定到 Listview itemssource
【发布时间】:2019-08-08 18:13:12
【问题描述】:

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

我不知道该怎么做

我试过了,但我得到 空引用异常

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

【问题讨论】:

  • 预期结果是例如。 item1 10 item2 20 item3 30 item4 40 列表数会根据需求动态变化
  • 如果您遇到 NullReferenceException,请包含相应的堆栈跟踪,以便我们帮助您缩小代码失败的范围
  • 你在哪里初始化dictionary?这些for 循环在哪里?
  • 什么类型的源数据,你能展示一下吗?也许你可以将源数据转换为 ViewModel 可以直接在 ListView 中使用。

标签: forms xamarin nullreferenceexception


【解决方案1】:

如果 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&lt;string,string&gt;)。

【讨论】:

  • 你能分享一下如何绑定标签和条目字段的代码
  • 谢谢..它正在工作..但是当我在输入字段中输入值并单击提交按钮时..我希望输入的值相对于键存储在字典中。
【解决方案2】:

由于不知道你的源数据是什么类型,如果源数据是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>

【讨论】:

    猜你喜欢
    • 2018-08-02
    • 2011-01-14
    • 2011-01-23
    • 2012-01-08
    • 2016-06-19
    • 2016-11-20
    • 1970-01-01
    • 1970-01-01
    • 2011-09-21
    相关资源
    最近更新 更多