簡體   English   中英

WP7 ListBox綁定不會更新

[英]WP7 ListBox Binding Doesn't Update

我已經在這個問題上坐了幾個小時了,我已經得到了部分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>

我有這個類(線程),其中包括應該在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; }
}

如果在將DataCotext更改為此特定線程之前將注釋加載到線程中。 會顯示注釋,但是當我在更改DataContext並導航到頁面后更新注釋時,注釋未顯示(我在xaml頁面的其余部分中將其他字段綁定到同一實例,並且它們只能正常工作。評論不起作用!

非常感謝您的幫助! 謝謝

您應該使用

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

代替

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

每當添加或刪除其中一項(在本例中為Comment)時,ObservableCollection都會向視圖發送更新通知。

注意:它不會更新Comment。 若要使項目綁定到Comment更新,Comment必須實現INotifyPropertyChanged。

您的屬性是一個簡單的List<T> 當事件發生變化時,需要使用事件向Silverlight發出信號。

添加/刪除項目時, List<T>不會引發任何事件,因此Silverlight無法檢測到新項目,因此不會更新UI。 進行此工作的最簡單方法通常是使用ObservableCollection<T>而不是列表。 該集合將引發Silverlight知道要收聽的事件。

請注意,為實現此目的,您不應該從U / I(分派器)線程之外的任何其他線程調用添加/刪除/清除,因為Silverlight控件不是線程安全的(並且在執行以下操作的線程上引發事件)添加/刪除/清除通話)。 為此,只需確保從SetComments方法調用Dispatcher.BeginInvoke (因為無論您使用哪種獲取機制,似乎都發生了回調)。

或者,您也可以在獲取注釋時重新生成一個全新的List對象,並在SetComments方法中引發NotifyPropertyCHanged事件,但這將導致丟失當前選擇並將列表重置為頂部,這可能不是您想要的做。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM