简体   繁体   中英

Binding public static observablecollection

I'm developing WP8 application and i have problem with binding static observablecollection after navigation back to pivot page from normal page.

The scenario like this i call webservice then i add the received data to observablecollection after that i made mylist.itemsource = my observablecollection to my list box inside pivot, its working perfect tell i build new page out of pivot when i navigation back from the new page to my pivot page the pivot reload all data from beginning so to avoid this problem i make flag to check if the data loaded or not , so when i make this its working fine but the problem when new data added to static observablecollection its not reflected to UI (Phone screen View).

Please help me to solve this problem and this part of my code:-

When the app start here to check the loaded data:-

public static ObservableCollection<DataTr> DataReceivedCollectionTr { get; set; }

private void load(object sender,RoutedEventArgs e)
{
    if (!IsDataLoaded)
    {
        GetOpentPos1(accountID);
    }          
    else
    {
        myListTrade.ItemsSource = DataReceivedCollectionTr;
    }
}

And here the call:

private void GetOpentPos (string accountID)
{
    DataReceivedCollectionTr = new  ObservableCollection<DataTr>();
    myListTrade.ItemsSource = DataReceivedCollectionTr;

    string result1;
    try
    {
        var request = HttpWebRequest.Create(new Uri("http://MyIP/vertexweb10/webservice.svc/GetOpenPositions?AccountId="+accountID)) as HttpWebRequest;

        request.Method = "GET";

        if (request.Headers == null)
        {
            request.Headers = new WebHeaderCollection();
        }
        request.Headers[HttpRequestHeader.IfModifiedSince] = DateTime.UtcNow.ToString();
        request.CookieContainer = cookieJar2;
        request.BeginGetResponse(ar =>
            {
                HttpWebRequest req2 = (HttpWebRequest)ar.AsyncState;
                using (var response = (HttpWebResponse)req2.EndGetResponse(ar))
                {
                    using (Stream stream = response.GetResponseStream())
                    {
                        using (var reader = new StreamReader(stream))
                        {
                            var outerRoot4 = JsonConvert.DeserializeObject<OuterRootObject4>(reader.ReadToEnd());
                            JArray jsonArray = JArray.Parse(outerRoot4.d);
                            JToken jsonArray_Item = jsonArray.First;

                            DispatchInvoke(() =>
                            {
                                while (jsonArray_Item != null)
                                {
                                    int PosID = jsonArray_Item.Value<int>("ID");
                                    if (PosID > 0)
                                    {
                                        string SymbolNameTra = jsonArray_Item.Value<string>;
                                        // Here I add the Data 
                                        DataReceivedCollectionTr.Add(new DataTr() { SymbolNameTr = SymbolNameTra});
                                    }

                                    jsonArray_Item = jsonArray_Item.Next;
                                }
                            });
                        }
                    }
                }
            }, request);
    }
}

And this is the XAML code:-

<Grid Background="#FF9AB5F9"
      x:Name="TradePanel"
      Grid.Row="1"
      Margin="0,70,0,-5">
    <ListBox Cursor="Hand"
             BorderBrush="Black"
             BorderThickness="1"
             Name="myListTrade"
             Background="#FF9AB5F9"
             Margin="0,-17,0,321">
        <ListBox.ItemContainerStyle>
            <Style TargetType="ListBoxItem">
                <Setter Property="HorizontalContentAlignment"
                        Value="Stretch" />
            </Style>
        </ListBox.ItemContainerStyle>
        <ListBox.ItemTemplate>
            <DataTemplate>
                <Grid Margin="25,25,0,0">
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition Width="2*" />
                        <ColumnDefinition Width="1*" />
                        <ColumnDefinition Width="1*" />
                        <ColumnDefinition Width="1*" />
                        <ColumnDefinition Width="0" />
                    </Grid.ColumnDefinitions>
                    <Grid.RowDefinitions>
                        <RowDefinition />
                    </Grid.RowDefinitions>
                    <TextBlock x:Name="SymNameTr"
                               Text="{Binding  SymbolNameTr}"
                               Grid.Row="0"
                               Grid.Column="0"
                               HorizontalAlignment="Left"
                               Foreground="White"
                               FontSize="18"
                               FontWeight="Bold"
                               Margin="5,5,0,0" />
                </Grid>
            </DataTemplate>
        </ListBox.ItemTemplate>
    </ListBox>
</Grid>

Please help me if any other code needed tell me so i can edit the question

The problem is you keep calling:

DataReceivedCollectionTr = new  ObservableCollection<DataTr>();
myListTrade.ItemsSource = DataReceivedCollectionTr;

in multiple places. You're doing this for every ListBox you assign a name to and you're doing it in multiple places. This is breaking bindings and reassigning, and the controls can't keep up with it. Instead, just make a field that is initialized when the control is created.

private static ObservableCollection<DataTr> _drCollTr = new ObservableCollection<DataTr>();
public static ObservableCollection<DataTr> DataReceivedCollectionTr
{
    get
    {
        return _drCollTr;
    }
}

then call DataRecievedCollectionTr 's .Add and .Remove/.Clear() functions to update the list. Once you initially set the ItemsSource, all you have to do is change the list itself instead of the control's ItemsSource.

I know this is the answer, since I fixed your code myself via TeamViewer :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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