数据绑定到列表框

3

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

        }

我试图将"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"绑定到列表框的想法?

非常感谢任何帮助。

1个回答

0

ListBox的ItemsSource属性不应该指向一个字符串,比如a.text,而是应该指向一个ObservableCollection。

可以尝试以下步骤:

1. 从INotifyPropertyChanged派生代码类。

2. 你可以从这里获取ObservableList或者使用ObservableCollection。

3. 然后使用以下代码(未经测试,但可能有效):

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

第四步:在字段顶部,您必须使用“using”语句导入ObservableList。
然后,将listbox的ItemSource绑定到此列表,并使TextBlock的Binding仅绑定到默认DataContext,该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不是很确定。 - qU3st
抱歉回复晚了。但我认为你误解了我的问题。 "a.text" 不是要转换为字符串。我希望将 "a.text" 绑定到可观察集合中。附言: "a.text" 是从我的 JSON 响应中提取的字符串。 - qU3st
我按照所有步骤进行了操作。但是foreach应该在方法中吗?错误:类、结构或接口成员声明中的无效标记“foreach”。 - qU3st
当然,这必须在一个方法中!我从你的问题中复制了这个,我猜你应该知道你的代码来自哪里。请不要再问任何可以由C#初学者教程回答的问题。 - Akku
正如我所说,请谷歌一下你可能缺乏的基本编程知识问题。如果你无法自己解决这个简单的问题(不仅在C#/.NET中,而且在其他编程语言中也存在),那么最好不要创建任何应用程序。抱歉,但这是我在此答案中输入的最后几个字符。 - Akku
显示剩余5条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接