我正在尝试构建一个简单的应用程序来显示API调用的结果。我似乎无法弄清楚如何将我的结果绑定到我的数据模板。
我在这个TestApp中寻找的行为是,当按下按钮时,列表视图会显示每个代表的名称,参与方和状态。
namespace TestApp
{
public class Reps
{
public Rep[] results { get; set; }
}
public class Rep
{
public string name { get; set; }
public string party { get; set; }
public string state { get; set; }
public string district { get; set; }
public string phone { get; set; }
public string office { get; set; }
public string link { get; set; }
public Rep() { }
public Rep(string name, string party, string state)
{
this.name = name;
this.party = party;
this.state = state;
}
}
}
namespace TestApp
{
public sealed partial class MainPage : Page
{
public ObservableCollection<Rep> Representative = new ObservableCollection<Rep>();
public MainPage()
{
this.InitializeComponent();
}
protected override void OnNavigatedTo(NavigationEventArgs e)
{
listView1.DataContext = Representative;
}
private async void Button_Click(object sender, RoutedEventArgs e)
{
var uri = new Uri("http://whoismyrepresentative.com/getall_mems.php?zip=31023&output=json");
var request = WebRequest.CreateHttp(uri);
request.Method = "GET";
request.Accept = "application/json";
var response = await request.GetResponseAsync();
var stream = response.GetResponseStream();
var deserializer = new DataContractJsonSerializer(typeof(Reps));
Reps rps = (Reps)deserializer.ReadObject(stream);
for (int i = 0; i < rps.results.Length; i++)
{
Rep newRep = new Rep { name = rps.results[i].name.ToString(),
party = rps.results[i].party.ToString(),
state = rps.results[i].state.ToString() };
Representative.Add(newRep);
Debug.WriteLine(rps.results[i].name.ToString());
}
}
}
}
<Grid Background="{StaticResource ApplicationPageBackgroundThemeBrush}">
<Button Content="Button"
HorizontalAlignment="Left"
Margin="275,212,0,0"
VerticalAlignment="Top"
Click="Button_Click" />
<Grid HorizontalAlignment="Left"
Height="293"
Margin="524,133,0,0"
VerticalAlignment="Top"
Width="399">
<ListView x:Name="listView1" ItemsSource="{Binding Representative}">
<ListView.ItemTemplate>
<DataTemplate>
<StackPanel>
<TextBlock Text="{Binding name}"
FontSize="20"
Foreground="White"/>
<TextBlock Text="{Binding party}"
FontSize="20"
Foreground="White"/>
<TextBlock Text="{Binding state}"
FontSize="20"
Foreground="White"/>
</StackPanel>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</Grid>
答案 0 :(得分:0)
设置ListView的DataContext仅设置绑定的上下文对象,但它本身不是绑定。因此,只需替换
行listView1.DataContext = Representative;
与
listView1.ItemsSource = Representative;