OrElse
OrElse

Reputation: 9969

How can i update a ListBox from a static class?

My XAML markup is

   <Grid x:Name="gdTest" HorizontalAlignment="Stretch" VerticalAlignment="Stretch"  Margin="5,0,5,0" >
       <ListBox Width="400" Margin="10" x:Name="lstDemo">
          <ListBox.ItemTemplate>
             <DataTemplate>
                <StackPanel Orientation="Horizontal">
                   <TextBlock Text="{Binding Path=id}" Margin="20" />
                   <TextBlock Text="{Binding Path=name}" Margin="20"/>
                </StackPanel>
             </DataTemplate>
          </ListBox.ItemTemplate>
        </ListBox>
   </Grid>

My super class is

public class SuperClass
    {
        public Arguments arguments;

        public class Stat
        {
            public int downloadCount;
        }

        public class Files
        {
            public int id;
            public string name;
            public List<Stat> SomeStats;
        }

        public class Arguments
        {
            public List<Files> Files;
        }
    }

In the App Class i declared my SuperClass as static. (The App.SuperClass gets filled in intervals of a dispatch timer).

public partial class App : Application
{
   public static SuperClass SuperClass = new SuperClass();
}

And finally when i bind the list of the static class to the ListBox, nothing is displayed in the emulator.

lstDemo.ItemsSource = App.SuperClass.arguments.Files;

What am i doing wrong here?

Upvotes: 0

Views: 153

Answers (2)

karolL
karolL

Reputation: 66

Instead of using public fields use automatic properties. Use ObservableCollection for ItemsSource binding, so your listbox is notified when add/remove event occurs.

public class SuperClass 
{
    public Arguments Args { get; set; }

    public class Stat
    {
        public int DownloadCount { get; set; }
    }

    public class File
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public List<Stat> SomeStats { get; set; }
    }

    public class Arguments 
    {
        public ObservableCollection<File> Files { get; set; }
    }
}

Upvotes: 4

loopedcode
loopedcode

Reputation: 4893

Change the List to ObservableCollection. Strandard list collection does not do Notification on add/remove as such on UI won't get updated.

public class Arguments
{
       public ObservableCollection<Files> Files;
}

Also, instead of directly setting ItemsSource this way, better approach would be to use Xaml Binding of ItemsSource with a ViewModel.

Upvotes: 0

Related Questions