无法使用mvvm体系结构将数据绑定到windows phone中的列表框

无法使用mvvm体系结构将数据绑定到windows phone中的列表框,mvvm,windows-phone-7.1,Mvvm,Windows Phone 7.1,我试图通过实现mvvm模式将json对象的数据收集从异步回调响应绑定到windows phone中的listbox…我能够将数据收集到observablecollectionm对象,但无法将其绑定到.xaml页面中的UI listbox控件 public Countries() { InitializeComponent(); if (App.countrylistVM == null) App.countrylistVM = new countryListVi

我试图通过实现mvvm模式将json对象的数据收集从异步回调响应绑定到windows phone中的listbox…我能够将数据收集到observablecollectionm对象,但无法将其绑定到.xaml页面中的UI listbox控件

public Countries()
{
    InitializeComponent();

    if (App.countrylistVM == null)
        App.countrylistVM = new countryListViewModel();

    DataContext = App.countrylistVM;
}

protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
{
    base.OnNavigatedTo(e);

    if (!App.countrylistVM.IsDataLoaded)
    {
        App.countrylistVM.Loadcountries();
        App.countrylistVM.IsDataLoaded = true;
    }
}
  <ListBox x:Name="lstcountries" 
                 Margin="0,0,-12,0"
                 ItemsSource="{Binding Countrylist}"
                 SelectedItem="{Binding Selectedcity, Mode=TwoWay}"
                 SelectionChanged="lstcountries_SelectionChanged" Background="white">
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <StackPanel Orientation="Vertical" Background="Black">
                        <TextBlock Text="{Binding Countriesdata.Countryid}" Foreground="Black" 
                            Visibility="Collapsed"/>
                        <TextBlock Text="{Binding Countriesdata.Countryname}" Foreground="Black"
                           />
                    </StackPanel>
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>
下面是app.xaml中的代码

 public static countryListViewModel countrylistVM { get; set; }
下面是countries.xaml页面中的代码

public Countries()
{
    InitializeComponent();

    if (App.countrylistVM == null)
        App.countrylistVM = new countryListViewModel();

    DataContext = App.countrylistVM;
}

protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
{
    base.OnNavigatedTo(e);

    if (!App.countrylistVM.IsDataLoaded)
    {
        App.countrylistVM.Loadcountries();
        App.countrylistVM.IsDataLoaded = true;
    }
}
  <ListBox x:Name="lstcountries" 
                 Margin="0,0,-12,0"
                 ItemsSource="{Binding Countrylist}"
                 SelectedItem="{Binding Selectedcity, Mode=TwoWay}"
                 SelectionChanged="lstcountries_SelectionChanged" Background="white">
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <StackPanel Orientation="Vertical" Background="Black">
                        <TextBlock Text="{Binding Countriesdata.Countryid}" Foreground="Black" 
                            Visibility="Collapsed"/>
                        <TextBlock Text="{Binding Countriesdata.Countryname}" Foreground="Black"
                           />
                    </StackPanel>
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>
下面是模型的代码

public class Model: INotifyPropertyChanged
{
    private Countriesdata countries;

    public Countriesdata Countries
    {
        get { return countries; }
        set
        {
            if (countries != value)
            {
                countries = value;
                RaisePropertyChanged("Countries");
            }
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;

    public void RaisePropertyChanged(string propname)
    {
        if (PropertyChanged != null)
            PropertyChanged(this, new PropertyChangedEventArgs(propname));
    }
}
}

以下是viewmodel的代码

public class countryListViewModel : INotifyPropertyChanged
{
    HttpWebRequest crequest;
    HttpWebResponse cresponse;

    private bool isDataLoaded = false;

    public bool IsDataLoaded
    {
        get { return isDataLoaded; }

        set
        {
            if (isDataLoaded != value)
            {
                isDataLoaded = value;
                RaisePropertyChanged("IsDataLoaded");
            }
        }
    }

    private Countriesdata countries;

    public Countriesdata Countries
    {
        get { return countries; }
        set
        {
            if (countries != value)
            {
                countries = value;
                RaisePropertyChanged("Countries");
            }
        }
    }

    private ObservableCollection<Countriesdata> countrylist;

    public ObservableCollection<Countriesdata> Countrylist
    {
        get { return countrylist; }
        set
        {
            if (countrylist != value)
            {
                countrylist = value;
                RaisePropertyChanged("Countrylist");
            }
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;

    public void RaisePropertyChanged(string propname)
    {
        if (PropertyChanged != null)
            PropertyChanged(this, new PropertyChangedEventArgs(propname));
    }

    public void Loadcountries()
    {
        try
        {
            crequest = (HttpWebRequest)WebRequest.Create(serviceurls.getcountries);
            crequest.Accept = "application/json";
            IAsyncResult cresult = (IAsyncResult)crequest.BeginGetResponse(new AsyncCallback(Responsecallbackcountries), crequest);
        }
        catch (Exception e)
        {
        }
    }

    private void Responsecallbackcountries(IAsyncResult cresult)
    {
        try
        {
            string countryresult = string.Empty;
            cresponse = (HttpWebResponse)crequest.EndGetResponse(cresult);
            using (var Stream = cresponse.GetResponseStream())
            {
                using (var Reader = new StreamReader(Stream))
                {
                    countryresult = Reader.ReadToEnd();
                }
                JObject Country = JObject.Parse(countryresult);
                JArray Root = (JArray)Country["Countries"];

                if (Root.Count != 0)
                {
                    countrylist = new ObservableCollection<Countriesdata>();
                    var Dictionary = Root.ToDictionary(x => x, x => x);
                    JToken Tctry;

                    foreach (var cntry in Dictionary)
                    {
                        Tctry = cntry.Value;
                        countrylist.Add(
                            new Countriesdata
                            {
                                Countryid = Convert.ToString(Tctry["ID"]),
                                Countryname = Convert.ToString(Tctry["Name"])

                            });
                    }
                    System.Windows.Deployment.Current.Dispatcher.BeginInvoke(() =>
                    {
                        Views.Countries vc = new Views.Countries();
                    });
                }
            }
        }
        catch (Exception e)
        {
        }
    }
}
公共类countryListViewModel:INotifyPropertyChanged
{
HttpWebRequest crequest;
HttpWebResponse;
private bool isDataLoaded=false;
公共布尔值已加载
{
获取{return isDataLoaded;}
设置
{
如果(isDataLoaded!=值)
{
isDataLoaded=值;
RaisePropertyChanged(“IsCatalLoaded”);
}
}
}
私营国家数据国家;
公共国家数据国家
{
获取{返回国家;}
设置
{
如果(国家!=值)
{
国家=价值;
RaiseProperty变更(“国家”);
}
}
}
私人可观察收集国家清单;
公共可观察收集国家/地区列表
{
获取{return countrylist;}
设置
{
如果(countrylist!=值)
{
countrylist=值;
RaisePropertyChanged(“Countrylist”);
}
}
}
公共事件属性更改事件处理程序属性更改;
public void RaisePropertyChanged(字符串propname)
{
if(PropertyChanged!=null)
PropertyChanged(这是新PropertyChangedEventArgs(propname));
}
公共服务(国家)
{
尝试
{
crequest=(HttpWebRequest)WebRequest.Create(serviceURL.getcountries);
crequest.Accept=“application/json”;
IAsyncResult cresult=(IAsyncResult)crequest.BeginGetResponse(新的AsyncCallback(Responsecallbackcountries),crequest);
}
捕获(例外e)
{
}
}
私人无效响应CallBackCountries(IAsyncResult)
{
尝试
{
string countryresult=string.Empty;
Response=(HttpWebResponse)crequest.EndGetResponse(cresult);
使用(var Stream=response.GetResponseStream())
{
使用(变量读取器=新的流读取器(流))
{
countryresult=Reader.ReadToEnd();
}
JObject Country=JObject.Parse(countryresult);
JArray根=(JArray)国家[“国家];
如果(Root.Count!=0)
{
countrylist=新的ObservableCollection();
var Dictionary=Root.ToDictionary(x=>x,x=>x);
JToken-Tctry;
foreach(字典中的变量cntry)
{
Tctry=cntry.Value;
国家列表。添加(
新国家数据
{
Countryid=Convert.ToString(Tctry[“ID”]),
Countryname=Convert.ToString(Tctry[“Name”])
});
}
System.Windows.Deployment.Current.Dispatcher.BeginInvoke(()=>
{
Views.Countries vc=新视图.Countries();
});
}
}
}
捕获(例外e)
{
}
}
}
下面是.xaml页面的代码

public Countries()
{
    InitializeComponent();

    if (App.countrylistVM == null)
        App.countrylistVM = new countryListViewModel();

    DataContext = App.countrylistVM;
}

protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
{
    base.OnNavigatedTo(e);

    if (!App.countrylistVM.IsDataLoaded)
    {
        App.countrylistVM.Loadcountries();
        App.countrylistVM.IsDataLoaded = true;
    }
}
  <ListBox x:Name="lstcountries" 
                 Margin="0,0,-12,0"
                 ItemsSource="{Binding Countrylist}"
                 SelectedItem="{Binding Selectedcity, Mode=TwoWay}"
                 SelectionChanged="lstcountries_SelectionChanged" Background="white">
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <StackPanel Orientation="Vertical" Background="Black">
                        <TextBlock Text="{Binding Countriesdata.Countryid}" Foreground="Black" 
                            Visibility="Collapsed"/>
                        <TextBlock Text="{Binding Countriesdata.Countryname}" Foreground="Black"
                           />
                    </StackPanel>
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>

您的数据模板引用的是模型,而不是列表框绑定到的集合中的项

相反,请尝试:

<DataTemplate>
    <StackPanel Orientation="Vertical">
        <TextBlock Text="{Binding Countryid}" Visibility="Collapsed"/>
        <TextBlock Text="{Binding Countryname}" />
    </StackPanel>
</DataTemplate>


您的ObservableCollection是否被数据填充,而只有绑定不起作用?在App.xaml中,您在哪里创建countrylistVM?因为您共享的代码只显示它是一个属性,但没有创建它的实例。我的observablecollection对象已成功填充,但将其绑定到UI不起作用。我已在xaml.cs文件..的initializecomponent()中创建了countrylistVM的实例国家的方法。xaml…如果你能看到…不知道为什么它不起作用,你能帮我检查一下上面的代码并解决它吗?谢谢你的回答…我尝试了上面的方法…但它不起作用…你能让我知道我哪里出错了。你知道你正在将前景和背景都设置为黑色吗?