简体   繁体   English

WP7 ListBox绑定不会更新

[英]WP7 ListBox Binding Doesn't Update

I've been sitting on this problem for hours now, I've got this partial xaml code: 我已经在这个问题上坐了几个小时了,我已经得到了部分xaml代码:

<TextBlock Text="{Binding temprature}" Height="30" HorizontalAlignment="Left" Margin="13,119,0,0" Name="textBlock1" VerticalAlignment="Top" Width="68" />
            <TextBlock Height="30" HorizontalAlignment="Left" Name="commentsTextBlock" Text="Comments:" VerticalAlignment="Bottom" Margin="12,0,0,-31" />
            <ListBox Margin="2,785,-14,-33" ItemsSource="{Binding comments}" DataContext="{Binding}" Name="commentsListBox">
                <ListBox.ItemTemplate>
                    <DataTemplate>
                        <StackPanel Orientation="Horizontal" Margin="0,0,0,17">
                            <StackPanel Width="311">
                                <TextBlock Text="{Binding poster_username}" TextWrapping="NoWrap" Style="{StaticResource PhoneTextSubtleStyle}" TextTrimming="WordEllipsis" Width="Auto" Foreground="White" FontFamily="Segoe WP Semibold" />
                                <TextBlock Text="{Binding comment_text}" TextWrapping="Wrap" Margin="12,-6,12,0" Style="{StaticResource PhoneTextSubtleStyle}" TextTrimming="WordEllipsis" MaxHeight="100" />
                            </StackPanel>
                        </StackPanel>
                    </DataTemplate>
                </ListBox.ItemTemplate>
            </ListBox>

And I have this class (Thread) which include a List of comments that should be displayed in the ListBox. 我有这个类(线程),其中包括应该在ListBox中显示的注释列表。

    public class Thread : INotifyPropertyChanged
{
    public string title { get; set; }
    public string deal_link { get; set; }
    public string mobile_deal_link { get; set; }
    public string deal_image { get; set; }
    public string deal_image_highres { get; set; }
    public string description { get; set; }
    public string submit_time { get; set; }
    public bool hot_date { get; set; }
    public string poster_name { get; set; }
    public double temperature { get; set; }
    public double price { get; set; }
    public int timestamp { get; set; }
    public string expired { get; set; }
    public Forum forum { get; set; }
    public Category category { get; set; }
    public object merchant { get; set; }
    public object tags { get; set; }
    public int thread_id { get; set; }
    public string visit_link { get; set; }
    public string hot_time { get; set; }
    public int comment_count { get; set; }
    public string availability { get; set; }
    public string can_vote { get; set; }
    public string seen { get; set; }

    public List<Comment> comments { get; set; }
    public event PropertyChangedEventHandler PropertyChanged;

    public void Convert2Unicode()
    {
        UnicodeEncoding unicode = new UnicodeEncoding();
        Byte[] encodedBytes = unicode.GetBytes(title);
        title = String.Format("[{0}]", title);


    }


    private void NotifyPropertyChanged(String propertyName)
    {
        PropertyChangedEventHandler handler = PropertyChanged;
        if (null != handler)
        {
            handler(this, new PropertyChangedEventArgs(propertyName));
        }
    }

    public void SetComments(string content)
    {
        PaginatedComments commentsList;
        this.comments.Clear();

        DataContractJsonSerializer serializer =
        new DataContractJsonSerializer(typeof(PaginatedComments));
        using (MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(content)))
        {
            commentsList = (PaginatedComments)serializer.ReadObject(ms);
        }


        foreach (var thread in commentsList.data.comments)
        {
            this.comments.Add(thread);
        }

    }
    public Thread()
    {
        comments = new List<Comment>();

    }
    public void addComments()
    {
        List<string> parameters = new List<string>();
        parameters.Add("thread_id=" + thread_id);
        parameters.Add("results_per_page=10");
        parameters.Add("page=1");
        // Set the data context of the listbox control to the sample data
        APICalls.makeRequest(APICalls.ViewingPaginatedComments, parameters, SetComments);

    }
    //
    // Sets the "Seen" variable depending if the item is new (since the last time the application was opened
    //
    public void updateNewItems()
    {
        try
        {
            int last_seen = (int)IsolatedStorageSettings.ApplicationSettings["lastrun"];

            if (last_seen < timestamp)
            {
                seen = "New";
            }
            else
            {
                seen = "";
            }
        }
        catch (System.Exception e)
        {
            IsolatedStorageSettings.ApplicationSettings["lastrun"] = APICalls.GetIntTimestamp();
            IsolatedStorageSettings.ApplicationSettings.Save();
            MessageBox.Show(e.Message);
        }

        IsolatedStorageSettings.ApplicationSettings["lastrun"] = APICalls.GetIntTimestamp();
        IsolatedStorageSettings.ApplicationSettings.Save();

    }
}
public class Comment
{
    public string poster_username { get; set; }
    public string post_date { get; set; }
    public string comment_text { get; set; }
    public int timestamp { get; set; }
    public int like_count { get; set; }
    public string comment_edit_text { get; set; }
}

public class CommentData
{
    public List<Comment> comments { get; set; }
    public int comment_count { get; set; }
    public int total_comments { get; set; }
}

public class PaginatedComments
{
    public string response_status { get; set; }
    public CommentData data { get; set; }
}

If I load the comments into the Thread before changing the DataCotext to this specific thread. 如果在将DataCotext更改为此特定线程之前将注释加载到线程中。 the comments are shown, but when I update the comments after changing the DataContext and navigating to the page the comments are not shown (I have other fields in the rest of the xaml page that are binded to the same instance and they work perfectly. only the comments don't work! 会显示注释,但是当我在更改DataContext并导航到页面后更新注释时,注释未显示(我在xaml页面的其余部分中将其他字段绑定到同一实例,并且它们只能正常工作。评论不起作用!

I really appreciate your help! 非常感谢您的帮助! Thanks 谢谢

You should be using 您应该使用

public ObservableCollection<Comment> comments{ get; set;}

instead of 代替

public List<Comment> comments { get; set; } 

The ObservableCollection sends update notices to the view anytime one of the items(in this case a Comment ) is added or removed. 每当添加或删除其中一项(在本例中为Comment)时,ObservableCollection都会向视图发送更新通知。

Note: It won't update the Comment . 注意:它不会更新Comment。 To have the items bound to the Comment update, Comment has to implement INotifyPropertyChanged. 若要使项目绑定到Comment更新,Comment必须实现INotifyPropertyChanged。

Your property is a simple List<T> . 您的属性是一个简单的List<T> Silverlight needs to be signaled when something changes, using events. 当事件发生变化时,需要使用事件向Silverlight发出信号。

A List<T> does not raise any event when items are being added/removed, so Silverlight cannot detect the new items and thus does not update the UI. 添加/删除项目时, List<T>不会引发任何事件,因此Silverlight无法检测到新项目,因此不会更新UI。 The simplest way to make this work is usually to use an ObservableCollection<T> instead of a list. 进行此工作的最简单方法通常是使用ObservableCollection<T>而不是列表。 This collection will raise events that Silverlight knows to listen to. 该集合将引发Silverlight知道要收听的事件。

Please note that for this to work you should not call Add/Remove/Clear from any other thread than the U/I (Dispatcher) thread, since Silverlight controls are not thread-safe (and the events are raised on the thread that performs the Add/Remove/Clear call). 请注意,为实现此目的,您不应该从U / I(分派器)线程之外的任何其他线程调用添加/删除/清除,因为Silverlight控件不是线程安全的(并且在执行以下操作的线程上引发事件)添加/删除/清除通话)。 To do that, simply make sure you call Dispatcher.BeginInvoke from your SetComments method (since it seems to be a callback happening from whatever your fetching mechanism is). 为此,只需确保从SetComments方法调用Dispatcher.BeginInvoke (因为无论您使用哪种获取机制,似乎都发生了回调)。

Alternatively, you could also regenerate a brand new List object when fetching comments, and raise the NotifyPropertyCHanged event in the SetComments method, but that would lead to losing the current selection and resetting your list to the top, which is probably not what you want to do. 或者,您也可以在获取注释时重新生成一个全新的List对象,并在SetComments方法中引发NotifyPropertyCHanged事件,但这将导致丢失当前选择并将列表重置为顶部,这可能不是您想要的做。

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

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