简体   繁体   English

WP7列表框绑定无法正常工作

[英]WP7 listbox binding not working properly

A noob error for sure (I started yesterday afternoon developing in WP7), but I'm wasting a lot time on it. 毫无疑问,是一个菜鸟错误(我昨天下午开始在WP7中进行开发),但是我在此上浪费了很多时间。
I post my class and a little part of my code: 我发布了我的课程和部分代码:

public class ChronoLaps : INotifyPropertyChanged
{
    private ObservableCollection<ChronoLap> laps = null;

    public int CurrentLap
    {
        get { return lap; }
        set
        {
            if (value == lap) return;
            // Some code here ....
            ChronoLap newlap = new ChronoLap()
            {
                // Some code here ...
            };
            Laps.Insert(0, newlap);

            lap = value;
            NotifyPropertyChanged("CurrentLap");
            NotifyPropertyChanged("Laps");
        }
    }

    public ObservableCollection<ChronoLap> Laps { 
        get { return laps; }
        set
        {
            if (value == laps) return;
            laps = value;
            if (laps != null)
            {
                laps.CollectionChanged += delegate
                {
                    MeanTime = Laps.Sum(p => p.Time.TotalMilliseconds) / (Laps.Count * 1000);
                    NotifyPropertyChanged("MeanTime");
                };
            }
            NotifyPropertyChanged("Laps");
        }
    }
}

MainPage.xaml.cs MainPage.xaml.cs

public partial class MainPage : PhoneApplicationPage
{
    public ChronoLaps History { get; private set; }

    private void butStart_Click(object sender, EventArgs e)
    {
        History = new ChronoLaps();
        // History.Laps.Add(new ChronoLap() { Distance = 0 });

        LayoutRoot.DataContext = History;
    }
}

MainPage.xaml MainPage.xaml

<phone:PhoneApplicationPage>    
    <Grid x:Name="LayoutRoot" Background="Transparent">
        <Grid Grid.Row="2">
            <ScrollViewer Margin="-5,13,3,36" Height="758">
                <ListBox Name="lbHistory" ItemContainerStyle="{StaticResource ListBoxStyle}"
                         ItemsSource="{Binding Laps}" 
                         HorizontalAlignment="Left" Margin="5,25,0,0"
                         VerticalAlignment="Top" Width="444">
                    <ListBox.ItemTemplate>
                        <DataTemplate>
                            <StackPanel Orientation="Horizontal">
                                <TextBlock Text="{Binding Lap}" Width="40" />
                                <TextBlock Text="{Binding Time}" Width="140" />
                                <TextBlock Text="{Binding TotalTime}" Width="140" />
                                <TextBlock Text="{Binding Distance}" />
                            </StackPanel>
                        </DataTemplate>
                    </ListBox.ItemTemplate>
                </ListBox>
            </ScrollViewer>
        </Grid>
    </Grid>
</phone:PhoneApplicationPage>       

Problem is that when I add one or more items to History.Laps collection, my listbox is not refreshed and these items don't appear. 问题是,当我向History.Laps集合中添加一个或多个项目时,我的列表框没有刷新,并且这些项目没有出现。
But if I remove comment on // History.Laps.Add(new ChronoLap()... line, this item appear and so every other inserted later. 但是,如果我删除对// History.Laps.Add(new ChronoLap()...行的评论), // History.Laps.Add(new ChronoLap()...显示此项,并在以后插入其他项。
More: if I remove that comment and then write History.Laps.Clear() (before or after setting binding) binding is not working anymore. 更多:如果我删除该注释,然后编写History.Laps.Clear() (在设置绑定之前或之后),绑定将不再起作用。 It's like it gets crazy if collection is empty. 如果集合为空,这将变得疯狂。
I really don't understand the reason... 我真的不明白原因...

UPDATE AND SOLUTION : 更新和解决方案
If i move 如果我搬家

History = new ChronoLaps();
LayoutRoot.DataContext = History;

from butStart_Click to public MainPage() everything works as expected. butStart_Clickpublic MainPage()一切正常。
Can someone explain me the reason? 有人可以解释一下原因吗?

Actually I see no point of having a separate class for ChronoLaps. 实际上,我认为没有单独的ChronoLaps类是没有意义的。 Here is how I modified the code for MainPage.xaml.cs and everything seems to be working for me. 这是我修改MainPage.xaml.cs的代码的方式,一切似乎对我来说都是有效的。

public partial class MainPage : PhoneApplicationPage
    {
        public ObservableCollection<ChronoLap> Laps { get; set; }
        public double MeanTime { get; set; }

        // Constructor
        public MainPage()
        {
            InitializeComponent();
            Laps = new ObservableCollection<ChronoLap>();
            Laps.CollectionChanged += delegate
            {
                MeanTime = Laps.Sum(p => p.Time.TotalMilliseconds) / (Laps.Count * 1000);
            };
            DataContext = this;
            Loaded += (s, e) =>
                          {
                              Laps.Add(new ChronoLap() {Time = TimeSpan.FromSeconds(1000)});
                              Laps.Add(new ChronoLap() {Time = TimeSpan.FromSeconds(1000)});
                              Laps.Add(new ChronoLap() {Time = TimeSpan.FromSeconds(1000)});
                          };
        }
    }

Try binding DataContext and ItemSource for listbox.. 尝试为列表框绑定DataContext和ItemSource。

How i have done is.. 我是怎么做的..

 <ListBox x:Name="AppList" Background="White" DataContext="{Binding DisplayItem}" SelectionChanged="AppList_SelectionChanged" Height="500" Width="auto">
            <ListBox.ItemTemplate>
                <DataTemplate>
  </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>

And i dont know if it will help but still i will just post the code that i am using.. 而且我不知道这是否有帮助,但我仍然会发布我正在使用的代码。

ItemList.cs ItemList.cs


using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Media.Imaging;

namespace AppHouseLibrary { public class ItemList : IComparable { private string _name; public string WidgetName { get { return _name; } set { _name = value; } } public int ID { get; set; } private BitmapImage _Icon; public BitmapImage Icon { get { return _Icon; } set { _Icon = value; } } //public string arrow { get; set; } public BitmapImage arrow { get; set; } public int CompareTo(ItemList other) { return this.WidgetName.CompareTo(other.WidgetName); } } }


I have a UIManager.cs class in which am refreshing the data before i load it on the UI to the user.. 我有一个UIManager.cs类,在将数据加载到用户界面上之前先刷新其中的数据。

 using System; using System.ComponentModel; using System.Collections.ObjectModel; using System.Windows.Media.Imaging; using System.Collections.Generic; using StirLibrary.com.mportal.data.bean; using com.mportal.utils; using StirLibrary.com.mportal.utils; 

\n\n

namespace StirLibrary.com.UI { public class UIManager : INotifyPropertyChanged { private static UIManager instance = null; 命名空间StirLibrary.com.UI {公共类UIManager:INotifyPropertyChanged {私有静态UIManager实例= null; private static string TAG = "UIManager"; 私有静态字符串TAG =“ UIManager”;
BitmapImage arrowImage = Utils.returnImage(ImageUtils.ARROW); BitmapImage arrowImage = Utils.returnImage(ImageUtils.ARROW);

\n\n
  public List<ItemList> data = new List<ItemList>(); public static UIManager getInstance() { if (instance == null) { instance = new UIManager(); } return instance; } private ObservableCollection<ItemList> _displayItem = new ObservableCollection<ItemList>(); public ObservableCollection<ItemList> DisplayItem { get { return _displayItem; } } private UIManager() { } public event PropertyChangedEventHandler PropertyChanged; private void NotifyPropertyChanged(String PropertyName) { if (null != PropertyChanged) { PropertyChanged(this, new PropertyChangedEventArgs(PropertyName)); } } public WidgetBean[] serviceBeanList = null; public WidgetBean[] wheelBeanList = null; public WidgetBean getServiceWidgetBean(int selectedIndex) { try { if (serviceBeanList != null) { return serviceBeanList[selectedIndex]; } } catch (Exception e) { Logger.log(TAG, e.Message); } return null; } public WidgetBean getWheelWidgetBean(int selectedIndex) { try { if (wheelBeanList != null) { return wheelBeanList[selectedIndex]; } } catch (Exception e) { Logger.log(TAG, e.Message); } return null; } public void DisplayCatalog(string[] ServiceDisplayName, string[] WheelDisplayName, BitmapImage[] ServiceIcons, WidgetBean[] ServiceBeanList, WidgetBean[] WheelBeanList) { try { DisplayItem.Clear(); string disp1 = string.Empty; string name = ServiceDisplayName[0]; wheelBeanList = WheelBeanList; serviceBeanList = ServiceBeanList; for (int i = 0; i < ServiceDisplayName.Length; i++) { WidgetBean bean = serviceBeanList[i]; if (bean.isCategory()) { DisplayItem.Add(new ItemList { WidgetName = ServiceDisplayName[i], Icon = ServiceIcons[i], arrow = arrowImage }); } else { DisplayItem.Add(new ItemList { WidgetName = ServiceDisplayName[i], Icon = ServiceIcons[i] }); } } NotifyPropertyChanged("UI"); } catch (Exception e) { Logger.log(TAG,e.Message); } } public void DisplayCatalog(string[] displayName, BitmapImage[] icons, WidgetBean[] beanArray) { try { serviceBeanList = beanArray; DisplayItem.Clear(); for (int i = 0; i < displayName.Length; i++) { WidgetBean bean = serviceBeanList[i]; if (bean.isCategory()) { DisplayItem.Add(new ItemList { WidgetName = displayName[i], Icon = icons[i], arrow = arrowImage }); } else { DisplayItem.Add(new ItemList { WidgetName = displayName[i], Icon = icons[i] }); } } NotifyPropertyChanged("UI"); } catch (Exception e) { Logger.log(TAG,e.Message); } } } 
\n\n

} }

\n\n

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM