none
Can’t get my second Observablecollection to work RRS feed

  • Question

  • I have two ObservableCollections, and the first one I made is working fine. I added a new page, and need another ObservableCollection there. But this one won't add items to the listview.
              <ListView Name="diverseTable" ItemsSource="{x:Bind diverseCollection}"
                    <ListView.ItemTemplate>
                        <DataTemplate x:DataType="data:DiverseCollection">
                            <Grid Height="25">
                                <Grid.ColumnDefinitions>
                                    <ColumnDefinition Width="*" MinWidth="85"/>
                                    <ColumnDefinition Width="*" MinWidth="80"/>
                                    <ColumnDefinition Width="*" MinWidth="80"/>
                                </Grid.ColumnDefinitions>
                                <TextBlock Grid.Column="0" VerticalAlignment="Center" Text="{x:Bind DateDiverse}" />
                                <TextBlock Grid.Column="1" VerticalAlignment="Center" Text="{x:Bind Beskrivelse}"/>
                                <TextBlock Grid.Column="2" VerticalAlignment="Center" Text="{x:Bind PrisDiverse}"/>
                            </Grid>
                        </DataTemplate>
                    </ListView.ItemTemplate>
                </ListView>
    
    --------------------------------------
    
    public ObservableCollection<DiverseCollection> diverseCollection;
    
    diverseCollection = new ObservableCollection<DiverseCollection>();
    
    
        public class DiverseCollection
        {
            public string DateDiverse { get; set; }
            public string Beskrivelse { get; set; }
            public double PrisDiverse { get; set; }
        }
    
                    diverseCollection.Add(new DiverseCollection
                    {
                        DateDiverse = DatoDiverse.Date.ToString("dd-MM-yyyy"),
                        Beskrivelse = BeskrivelseDiverse.Text,
                        PrisDiverse = PrisDiverse.Text});
    
    
        public class TankningCollection
        {
            public string Date { get; set; }
            public int KmTaeller { get; set; }
            public double LiterTanket { get; set; }
            public double Pris { get; set; }
            public int KmKoert { get; set; }
            public double PrisPrLiter { get; set; }
            public double KmPrLiter { get; set; }
        }
    
    public ObservableCollection<TankningCollection> tankningCollection;
    tankningCollection = new ObservableCollection<TankningCollection>();
    
    tankningCollection.Add(new TankningCollection
                        {
                            Date = Dato.Date.ToString("dd-MM-yyyy"),
                            KmTaeller = KmTaeller.Text,
                            LiterTanket = LiterTanket.Text,
                            Pris = Pris.Text,
                            KmKoert = tanknkningCollection.LastOrDefault().KmTaeller,
                            PrisPrLiter = Pris.Text / LiterTanket.Text,
                            KmPrLiter = (KmTaeller.Text -tankningCollection.LastOrDefault().KmTaeller) / LiterTanket.Text });
    

    I have added code for both Collections.

    Like I said the first one 'tankningCollection' works fine. But 'diverseCollection' will not add to it's listview.

    I have went through them over and over and to me it's the same code, just with different boxes and properties. But I'm clearly missing something somewhere.

    Can anyone help ?

    Thanks

    Wednesday, September 4, 2019 5:14 PM

All replies

  • When you create that collection? By default x:Bind mode is OneTime and collection could be null at the moment when it tries to access it. If this is a reason, just add Mode=OneWay to your binding.
    Wednesday, September 4, 2019 8:45 PM
  • Hmmm What about instead of 

    public ObservableCollection<DiverseCollection> diverseCollection;
    
    diverseCollection = new ObservableCollection<DiverseCollection>();
    
    
        public class DiverseCollection
        {
            public string DateDiverse { get; set; }
            public string Beskrivelse { get; set; }
            public double PrisDiverse { get; set; }
        }

    you do

    public class DiverseCollection { public string DateDiverse { get; set; } public string Beskrivelse { get; set; } public double PrisDiverse { get; set; } }

    public ObservableCollection<DiverseCollection> diverseCollection;

    diverseCollection = new ObservableCollection<DiverseCollection>();

    The only thing i see different from what you showed is the order of how you create it.

    • Edited by Skittles2519 Thursday, September 5, 2019 5:06 AM added content
    Thursday, September 5, 2019 5:05 AM
  • Hi !

    I tried to add Mode=OneWay to the bindings, but it's still the same.

    I adds fine to the TankningsCollection and i wont add to the DiverseCollection.

    It's like it doesn't exist.

    If I'm trying to clear the list with 

    diverseCollection.Clear();

    It comes with an error:

    System.NullReferenceException: 'Object reference not set to an instance of an object.'
    <>4__this.diverseCollection was null.


    • Edited by Mr. T2 Thursday, September 5, 2019 4:14 PM
    Thursday, September 5, 2019 4:08 PM
  • Hi !

    On top of the code page for each page i define the Collection.

    And the properties is in a Class page.

    So I'm doing exactly the same for the to. just in different pages with different names.

    Thursday, September 5, 2019 4:10 PM
  • You either missed something in your code or it is old bug in Visual Studio. Sometimes when you edit XAML pages or code behind them, it stuck with old version of layout or code. When it happens, I usually do following: Build -> Clean Solution, close Visual Studio, delete binary folders like bin, obj, Release, Debug, x86, x64, ARM, open Visual Studio again and rebuild solution. If something is wrong with your code, you should post full code for that page here because snippets above look correct.
    Thursday, September 5, 2019 5:44 PM
  • Okay ! I tried that too now and it's still the same....So now I've add all the XAML and code for 'diverseCollection'

    ///XAML for my ListView in DiversePage:

                <ListView Name="diverseTable" ItemsSource="{x:Bind diverseCollection}"
                      IsItemClickEnabled="True" SelectionMode="Single" ScrollViewer.VerticalScrollMode="Auto">
                    <ListView.ItemContainerStyle>
                        <Style TargetType="ListViewItem">
                            <Setter Property="HorizontalContentAlignment" Value="Stretch" />
                        </Style>
                    </ListView.ItemContainerStyle>
                    <ListView.ItemTemplate>
                        <DataTemplate x:DataType="data:DiverseCollection">
                            <Grid Height="25">
                                <Grid.ColumnDefinitions>
                                    <ColumnDefinition Width="*" MinWidth="85"/>
                                    <ColumnDefinition Width="*" MinWidth="80"/>
                                    <ColumnDefinition Width="*" MinWidth="80"/>
                                </Grid.ColumnDefinitions>
                                <TextBlock Grid.Column="0" VerticalAlignment="Center" Style="{ThemeResource BaseTextBlockStyle}" Text="{x:Bind DateDiverse}" />
                                <TextBlock Grid.Column="1" VerticalAlignment="Center" Style="{ThemeResource BaseTextBlockStyle}" Text="{x:Bind Beskrivelse}"/>
                                <TextBlock Grid.Column="2" VerticalAlignment="Center" Style="{ThemeResource BaseTextBlockStyle}" Text="{x:Bind PrisDiverse}"/>
                            </Grid>
                        </DataTemplate>
                    </ListView.ItemTemplate>
                </ListView>

    ///My Class called 'Collections' : public class TankningCollection { public string Date { get; set; } public int KmTaeller { get; set; } public double LiterTanket { get; set; } public double Pris { get; set; } public int KmKoert { get; set; } public double PrisPrLiter { get; set; } public double KmPrLiter { get; set; } } public class DiverseCollection { public string DateDiverse { get; set; } public string Beskrivelse { get; set; } public double PrisDiverse { get; set; } } ///And last my DiversePage.xaml.cs :

        public sealed partial class DiversePage : Page
        {
            public ObservableCollection<DiverseCollection> diverseCollection;
            public Calculate calculate = new Calculate();
            public string filenameDiverse = "Diverse.txt";
            public DiversePage()
            {
                this.InitializeComponent();
                DatoDiverse.SelectedDate = DateTime.Today;
                diverseCollection = new ObservableCollection<DiverseCollection>();
            }
            private void Page_Loaded(object sender, RoutedEventArgs e)
            {
                Load_Diverse();
            }
            private void GodkendDiverse_Click(object sender, RoutedEventArgs e)
            {
                try
                {
                    diverseCollection.Add(new DiverseCollection
                    {
                        DateDiverse = DatoDiverse.Date.ToString("dd-MM-yyy"),
                        Beskrivelse = BeskrivelseDiverse.Text,
                        PrisDiverse = Convert.ToDouble(PrisDiverse.Text)
                    });
                    DatoDiverse.SelectedDate = DateTime.Today;
                    BeskrivelseDiverse.Text = "";
                    PrisDiverse.Text = "";
                }
                catch
                { }

                SaveDiverse();
                Calculate();
            }

    }





    • Edited by Mr. T2 Sunday, September 8, 2019 8:37 PM
    Sunday, September 8, 2019 8:31 PM
  • I still suspect x:Bind OneTime mode, what if we will do

     diverseCollection = new ObservableCollection<DiverseCollection>();

    before

     this.InitializeComponent();

    or declare it like this:

    public ObservableCollection<DiverseCollection> diverseCollection = new ObservableCollection<DiverseCollection>();


    Monday, September 9, 2019 12:27 PM
  • It's like it wont read that code. if I make a break point on top of it and 'step into' it jumps over the code

    public ObservableCollection<DiverseCollection> diverseCollection;

    And when i hoover over it, it just says 'null'.

    So it's not making the collection at all ?

    Has it something to do with the page ? that it's not the 'startup page' or something like that ?

    It's driving me crazy.!

    Tuesday, September 10, 2019 8:16 PM
  • Oh, can you attach zip archive with a project to reproduce it?
    Wednesday, September 11, 2019 8:12 AM
  • How do I attach it?

    I have made the .zip file ready.

    Wednesday, September 11, 2019 4:07 PM
  • GitHub is a good choice.
    Thursday, September 12, 2019 10:20 AM
  • Hi Again !

    I think this should work.

    I have uploaded the complete project.

    https://github.com/theistn/theistn.github.io/blob/master/Diesel.zip

    Friday, September 13, 2019 12:58 PM
  • Well, GitHub is famous zip files hosting. That collection is being set to null by some deserialization code in your project:

    Next time when you will have similar issue, you can just convert field to property and set breakpoint in the setter. Stack trace window will help you find what method called that setter.

    Friday, September 13, 2019 3:20 PM