C# 数据绑定到列表框

C# 数据绑定到列表框,c#,json,data-binding,C#,Json,Data Binding,“a.text”是从我的JSON响应中提取的。我试图在列表框中显示“a.text” List<Feature> features = App.dResult.directions[0].features; foreach (Feature f in features) { Attributes a = f.attributes; MessageBox.Show(a.text); d

“a.text”是从我的JSON响应中提取的。我试图在列表框中显示“a.text”

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;

        }
List features=App.dResult.directions[0]。功能;
foreach(特征中的特征f)
{
属性a=f.属性;
MessageBox.Show(a.text);
directionListBox.ItemsSource=a.text;
}
我尝试将“a.text”绑定到列表框,但没有显示

<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>

有谁能告诉我如何将“a.text”绑定到列表框


非常感谢您的帮助。

列表框的ItemsSource属性不应指向字符串(如.text),而应指向ObservableCollection

试着这样做:

第一:从INotifyPropertyChanged派生代码类

第二:您可以从ObservableCollection获取ObservableList,也可以使用ObservableCollection

第三:然后使用此代码(未经测试,但可能有效):

ObservableList featList=新的ObservableCollection();
公共事件属性更改事件处理程序属性更改;
public void InvokePropertyChanged(字符串propertyName)
{
PropertyChangedEventHandler处理程序=PropertyChanged;
if(handler!=null)handler(这是新的PropertyChangedEventArgs(propertyName));
}
公共观察专家专长列表
{
获取{return featList;}
设置
{
featList=值;
InvokePropertyChanged(“FeatList”);
}
}
列表功能=App.dResult.directions[0]。功能;
foreach(特征中的特征f)
{
属性a=f.属性;
//MessageBox.Show(a.text);
FeatList.add(a.text);
}
第四:在fild的顶部,您必须使用“using”语句来导入observeList

然后,将listbox的ItemSource绑定到此列表,并使TextBlock的绑定仅绑定到默认DataContext,即列表中的字符串:

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


在哪里可以应用这些代码?我对ObservableCollection不是很确定。只要把链接到ObservableList的代码放到一个文件中,放到你的项目中。上面的其余部分你应该直接输入你的代码。很抱歉回复得太晚。但我想你误解了我的问题。“a.text”不能转换为字符串。我希望将“a.text”绑定到observableCollection中。另外,“a.text”是从我的JSON响应中提取的字符串。这正是我提出的解决方案所做的。你试过了吗?(包括XAML?)?你是读了全部答案还是只是粘贴了代码?;-)如果仍然有错误,那是什么?
<ListBox x:Name="directionListBox" ItemsSource="{Binding FeatList}" >
        <ListBox.ItemTemplate>
            <DataTemplate>
                <StackPanel Orientation="Vertical">
                    <TextBlock Text="{Binding}" Style="{StaticResource PhoneTextTitle2Style}" />
                </StackPanel>
            </DataTemplate>
        </ListBox.ItemTemplate>
    </ListBox>