【问题标题】:unable to bind data to listbox in windows phone using mvvm architecture无法使用 mvvm 架构将数据绑定到 Windows Phone 中的列表框
【发布时间】:2012-11-09 23:26:54
【问题描述】:

我正在尝试通过实现 mvvm 模式将来自异步回调响应的 json 对象的数据集合绑定到 windows phone 中的列表框...我能够将数据集合获取到 observablecollectionm 对象但无法绑定它到 .xaml 页面中的 UI 列表框控件。

以下是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;
    }
}

以下是模型代码。

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

}

public class Countriesdata : INotifyPropertyChanged
{
    private string countryid;

    public string Countryid
    {
        get { return countryid; }
        set
        {
            if (countryid != value)
            {
                countryid = value;
                RaisePropertyChanged("Countryid");
            }
        }
    }

    private string countryname;

    public string Countryname
    {
        get { return countryname; }
        set
        {
           if (countryname != value)
           {
               countryname = value;
               RaisePropertyChanged("Countryname");
           }
        }
    }

下面是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)
        {
        }
    }
}

以下是 .xaml 页面的代码。

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

【问题讨论】:

  • 您的 ObservableCollection 是否被填充了数据,并且只有绑定不起作用?
  • 在您的 App.xaml 中,您在哪里创建 countrylistVM?因为您共享的代码仅显示它是一个属性,但没有创建它的实例。
  • 我的 observablecollection 对象已成功填充,但无法将其绑定到 UI。
  • 我在 xaml.cs 文件中创建了 countrylistVM 的实例。在 country.xaml 的 initializecomponent() 方法中...如果你能看到...不知道为什么它不起作用跨度>
  • 你能不能把我上面的代码看一遍,帮我解决一下。

标签: mvvm windows-phone-7.1


【解决方案1】:

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

请尝试:

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

【讨论】:

  • 感谢您的回复...我已尝试上述方法...但没有成功...请您告诉我哪里出错了。
  • 您是否意识到您将前景和背景都设置为黑色?
猜你喜欢
  • 1970-01-01
  • 2014-04-17
  • 2012-01-24
  • 2012-09-11
  • 1970-01-01
  • 2013-10-24
  • 1970-01-01
  • 2013-04-12
  • 1970-01-01
相关资源
最近更新 更多