xamluwpuwp-xamlflipview

Displaying bound data in a FlipView


I've declared a FlipView control in XAML, and I want to bind it to a collection source defined and populated in code behind (.cs file). Furthermore, the texblock is to display a specific property of an item in the collection.

XAML declaration of FlipView:

        <FlipView x:Name="FlipViewStudents" Grid.Row="1" Height="Auto" Width="Auto" ItemsSource="{x:Bind Students}">
            <FlipView.ItemTemplate>
                <DataTemplate>
                    <StackPanel Orientation="Vertical">
                        <TextBlock x:Name="StudentName" Text="{Binding Name}" FontSize="60" Foreground="Green" FontWeight="Bold" TextAlignment="Left"/>
                    </StackPanel>
                </DataTemplate>
            </FlipView.ItemTemplate>
        </FlipView>

C# codebehind (the .cs file belonging to this XAML file) definition of collection variable:

private List<SingleStudent> Students { get; set; }

Update: I'm initialising the collection variable in the Page_Loaded event handler:

Students = new List<SingleStudent>();

Furthermore, I'm using a DispatcherTimer with a 30 second tick interval, and I'm populating the collection variable inside the dispatcherTimer_Tick (when a tick happens) handler (after clearing it first):

Students.Clear();
var singleStudent = new SingleStudent()
{
    Name = "John",
    Grade = "B" 
};    
Students.Add(singleStudent);

As shown, the collection variable is both cleared and populated every 30 second. I was hoping the FlipView in the GUI would update itself whenever items were added to the collection.

I've debugged and checked that objects are added to the collection in code, but it is not appearing anything in the GUI.

As shown, SingleStudent is a class with different properties, including Name, which is the item property to display inside the FlipView.

I've tried using ObservableCollection too, but this will not show anything either. Help or hints appreciated.


Solution

  • As you mentioned you also see the same problem when using a ListView instead of a flipview when either using a List<SingleStudent> or ObservableCollection<SingleStudent>

    I did some tests and it turns out that initializing the collection in the Page_Loaded event messes up your databinding. Therefore you should define:

    private ObservableCollection<SingleStudent> Students = new ObservableCollection<SingleStudent>();
    

    or

    private ObservableCollection<SingleStudent> Students { get; set; }
    public TestPage() //Constructor of your page
    {
        Students = new ObservableCollection<SingleStudent>();
    }
    

    Furthermore, you see me using an ObservableCollection<SingleStudent>. You have to use this instead of a list. Using a List<SingleStudent> will not work since adding an item will not raise INotifyPropertyChanged therefore not updating the databinding.