我试图创建填充了我从REST服务获得的数据的ComboBox
。
在我的窗口中,我有获取数据和设置ViewModel的方法:
private void ComboBox_Loaded(object sender, RoutedEventArgs e)
{
String url = "http://localhost:8081/HTTP/testFrigoexim/prijem/getDodavatele";
WebClient client = new WebClient();
String response = client.DownloadString(url);
Dodavatele dodavatele;
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(Dodavatele));
using (var stream = new MemoryStream(Encoding.UTF8.GetBytes(response)))
{
dodavatele = (Dodavatele)serializer.ReadObject(stream);
}
ComboBoxDodavatele.DataContext = new ViewModel(dodavatele);
}
Class表示来自REST服务的数据:
namespace TestovaciAplikace.Prijem
{
[DataContract]
public class Dodavatele
{
[DataMember]
public List<Dodavatel> dodavatele { get; set; }
}
public class Dodavatel
{
public string CODE { get; set; }
}
}
和上一课,ViewModel
namespace TestovaciAplikace.Prijem
{
public class ViewModel : NotifyPropertyChanged
{
public Dodavatele dodavatele { get; set; }
public ViewModel(Dodavatele dodavatele)
{
this.dodavatele = dodavatele;
}
}
}
绑定到ComboBox是
<ComboBox Name="ComboBoxDodavatele" HorizontalAlignment="Left" Margin="109,10,0,0" VerticalAlignment="Top" Width="210" Height="35"
Loaded="ComboBox_Loaded" ItemsSource="{Binding dodavatele}" DisplayMemberPath="CODE"/
如果我运行程序,ComboBox
为空。如果我替换ny ViewModel
只返回简单的List<String>
它可以工作(如果我更改绑定属性),但我不能使用我的JSON数据。有什么建议吗?
答案 0 :(得分:1)
由于ViewModel和Dodavatele类都具有dodavatele
属性,因此ItemsSource Binding应该如下所示
ItemsSource="{Binding dodavatele.dodavatele}"