简体   繁体   中英

DataBinding to listbox

The "a.text" is extracted from my JSON Response. I am trying to display the "a.text" in the listbox.

List<Feature> features = App.dResult.directions[0].features;
        foreach (Feature f in features)
        {
            Attributes a = f.attributes;
            MessageBox.Show(a.text);
            directionListBox.ItemsSource = a.text;

        }

I tried using binding the "a.text" to the listbox but there is no display.

<ListBox x:Name="directionListBox" ItemsSource="{Binding a.text}" >
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <StackPanel Orientation="Vertical">
                        <TextBlock Text="{Binding a.text}" Style="{StaticResource PhoneTextTitle2Style}" />
                    </StackPanel>
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>

Can anyone provide me with some idea on how to bind the "a.text" to listbox?

Any help will be greatly appreciated.

The ItemsSource Property of a ListBox should not point to a String, like a.text, but to an ObservableCollection.

Try something like this:

1st: derive that code class from INotifyPropertyChanged.

2nd: You can get the ObservableList from here or use ObservableCollection instead.

3rd: Then use this code (untested, but might work):

ObservableList<String> featList = new ObservableCollection<String>();
public event PropertyChangedEventHandler PropertyChanged;

public void InvokePropertyChanged(string propertyName)
{
    PropertyChangedEventHandler handler = PropertyChanged;
    if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
}
public ObservableList<String> FeatList
{
    get { return featList; }
    set
    {
        featList = value;
        InvokePropertyChanged("FeatList");
    }
}
List<Feature> features = App.dResult.directions[0].features;
foreach (Feature f in features)
{
    Attributes a = f.attributes;
    //MessageBox.Show(a.text);
    FeatList.add(a.text);
}

4th: At the top of the fild you have to use a 'using' statement to import the ObservableList.

Then, bind the listbox'es ItemSource to this list, and make the TextBlock's Binding just bind to the default DataContext, which will be the string from the list:

<ListBox x:Name="directionListBox" ItemsSource="{Binding FeatList}" >
        <ListBox.ItemTemplate>
            <DataTemplate>
                <StackPanel Orientation="Vertical">
                    <TextBlock Text="{Binding}" Style="{StaticResource PhoneTextTitle2Style}" />
                </StackPanel>
            </DataTemplate>
        </ListBox.ItemTemplate>
    </ListBox>

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