简体   繁体   中英

cannot bind data to a listpicker, obtained from a json string in xaml for windows phone8 application

when I bind data to the listpicker, I get name displayed in selected item, but when the dropdown shows the whole item will be myProject.MyClass....something I am new to windows phone application development.. Can anyone help me with this?

here is my xaml code

<toolkit:ListPicker Header="Select Name" Name="listName" Tap="listName_Tap" VerticalAlignment="Center">
   <toolkit:ListPicker.ItemTemplate>
        <DataTemplate>
            <StackPanel>
            <TextBlock Text="{Binding name}"/>
            </StackPanel>
        </DataTemplate>
      </toolkit:ListPicker.ItemTemplate> 
</toolkit:ListPicker>

Here is my c# code

class MyClass
{
    public String name{ get; set; }
}

private void sendPostCompleted(object sender, UploadStringCompletedEventArgs e)     
{
    //e.result is my json string obtained from webservice([{name:hhh}{name:jkj}{name:jack}])
    var data = JsonConvert.DeserializeObject<MyClass[]>(e.Result.ToString()); 
    listName.ItemsSource = data;
}

I am not so sure but I think the problem is with the binding. You're binding an Array , instead of it try List :

var data = JsonConvert.DeserializeObject<List<MyClass>>(e.Result.ToString()); 

You also need to add JsonProperty to your class property ( ref ):

class MyClass
{
    [JsonProperty("name")]
    public String name{ get; set; }
}

Try this below code :

<toolkit:ListPicker Header="Select Name" Name="listName" Tap="listName_Tap" VerticalAlignment="Center" ItemsSource={Binding NamesList}>
   <toolkit:ListPicker.ItemTemplate>
        <DataTemplate>
            <StackPanel>
            <TextBlock Text="{Binding name}"/>
            </StackPanel>
        </DataTemplate>
      </toolkit:ListPicker.ItemTemplate> 
</toolkit:ListPicker>

In Code behind, Add the following :

private ObservableCollection<MyClass> _NamesList = new ObservableCollection<MyClass>();    
public ObservableCollection<MyClass> NamesList 
{ 
   get {return _NamesList} 
   set {_NamesList = value}
}

Add below code in constructor

this.DataContext = this;

Copy the array data to observablecollection

private void sendPostCompleted(object sender, UploadStringCompletedEventArgs e)     
    {
        //e.result is my json string obtained from webservice([{name:hhh}{name:jkj}{name:jack}])
        var data = JsonConvert.DeserializeObject<MyClass[]>(e.Result.ToString()); 

            foreach (var item in data)
            {
                NamesList.Items.Add(item);
            }
    }

Note : Use ObservableCollection for binding list UI controls for updating UI data while property changes.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM