Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XAML equivalent of a foreach

Tags:

c#

xaml

Ok so i am trying to pass list of items into a XAML-view in order to "loop" over them. I am used to working with html and have not really understood how to achieve this in XAML.

Here is the class containing Item and also a method that creates a list of Items which I wish to pass to the view:

public class Item
    {
        public int ItemId { get; set; }
        public string Name { get; set; }
        public int Age { get; set; }
        public string Description { get; set; }



        public List<Item> GetList()
        {

            var _test = new List<Item>();
            for (int i = 0; i < 10; i++)
            {
                var newItem = new Item()
                {
                    ItemId = i++,
                    Name = "Person",
                    Age = 30,
                    Description = "Description",

                };

                _test.Add(newItem);
            }

            return _test;
        } 
    }

My view consists of a XAML-template calles GroupDetailPage which consists of a listview to the left and a "detail-view" in the middle which is supposed to switch depending on what item from the list I pick. Here is the XAML for the list-view, untouched:

 <ListView
            x:Name="itemListView"
            AutomationProperties.AutomationId="ItemsListView"
            AutomationProperties.Name="Items"
            TabIndex="1"
            Grid.Row="1"
            Margin="-10,-10,0,0"
            Padding="120,0,0,60"
            ItemsSource="{Binding Source={StaticResource itemsViewSource}}"
            IsSwipeEnabled="False"
            SelectionChanged="ItemListView_SelectionChanged">
            <ListView.ItemTemplate>
                <DataTemplate>
                    <Grid Margin="6">
                        <Grid.ColumnDefinitions>
                            <ColumnDefinition Width="Auto"/>
                            <ColumnDefinition Width="*"/>
                        </Grid.ColumnDefinitions>
                        <Border Background="{ThemeResource ListViewItemPlaceholderBackgroundThemeBrush}" Width="60" Height="60">
                            <Image Source="{Binding ImagePath}" Stretch="UniformToFill" AutomationProperties.Name="{Binding Title}"/>
                        </Border>
                        <StackPanel Grid.Column="1" Margin="10,0,0,0">
                            <TextBlock Text="{Binding Title}" Style="{StaticResource TitleTextBlockStyle}" TextWrapping="NoWrap" MaxHeight="40"/>
                            <TextBlock Text="{Binding Subtitle}" Style="{StaticResource CaptionTextBlockStyle}" TextWrapping="NoWrap"/>
                        </StackPanel>
                    </Grid>
                </DataTemplate>
            </ListView.ItemTemplate>
            <ListView.ItemContainerStyle>
                <Style TargetType="FrameworkElement">
                    <Setter Property="Margin" Value="0,0,0,10"/>
                </Style>
            </ListView.ItemContainerStyle>
        </ListView>

Here is the Code-behind for the view. I guess I need to create a method here that gets my list of items and binds it to the view? I,ve been struggling a lot with this. Im probably to stuck in my MVC-thinking to be able to figure out how to go about this:

  public sealed partial class GroupDetailPage1 : Page
    {
        private NavigationHelper navigationHelper;
        private ObservableDictionary defaultViewModel = new ObservableDictionary();

        /// <summary>
        /// This can be changed to a strongly typed view model.
        /// </summary>
        public ObservableDictionary DefaultViewModel
        {
            get { return this.defaultViewModel; }
        }

        /// <summary>
        /// NavigationHelper is used on each page to aid in navigation and 
        /// process lifetime management
        /// </summary>
        public NavigationHelper NavigationHelper
        {
            get { return this.navigationHelper; }
        }

        public GroupDetailPage1()
        {
            this.InitializeComponent();

            // Setup the navigation helper
            this.navigationHelper = new NavigationHelper(this);
            this.navigationHelper.LoadState += navigationHelper_LoadState;
            this.navigationHelper.SaveState += navigationHelper_SaveState;

            // Setup the logical page navigation components that allow
            // the page to only show one pane at a time.
            this.navigationHelper.GoBackCommand = new SimpleMapping.Common.RelayCommand(() => this.GoBack(), () => this.CanGoBack());
            this.itemListView.SelectionChanged += itemListView_SelectionChanged;

            // Start listening for Window size changes 
            // to change from showing two panes to showing a single pane
            Window.Current.SizeChanged += Window_SizeChanged;
            this.InvalidateVisualState();
        }

        void itemListView_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (this.UsingLogicalPageNavigation())
            {
                this.navigationHelper.GoBackCommand.RaiseCanExecuteChanged();
            }
        }


        private void navigationHelper_LoadState(object sender, LoadStateEventArgs e)
        {
            // TODO: Assign a bindable group to Me.DefaultViewModel("Group")
            // TODO: Assign a collection of bindable items to Me.DefaultViewModel("Items")

            if (e.PageState == null)
            {
                // When this is a new page, select the first item automatically unless logical page
                // navigation is being used (see the logical page navigation #region below.)
                if (!this.UsingLogicalPageNavigation() && this.itemsViewSource.View != null)
                {
                    this.itemsViewSource.View.MoveCurrentToFirst();
                }
            }
            else
            {
                // Restore the previously saved state associated with this page
                if (e.PageState.ContainsKey("SelectedItem") && this.itemsViewSource.View != null)
                {
                    // TODO: Invoke Me.itemsViewSource.View.MoveCurrentTo() with the selected
                    //       item as specified by the value of pageState("SelectedItem")

                }
            }
        }

Can someone ponit me in the right direction here. Im trying to pass my list of items to the view and hoping that there is an equivalent of the foreach-loop or something similar? Thank you!

EDIT: In the constructor for the GroupDetailPage I added this code:

 var items = new ObservableCollection<Item>();
        items = model.GetList();
        DataContext = items;

Does this now mean that I can access the in my view?

I added this snippet of code from the link:

 <ItemsControl ItemsSource="{Binding}">
                <ItemsControl.ItemTemplate>
                    <DataTemplate>
                        <StackPanel>
                            <TextBlock Text="{Binding }"></TextBlock>

                        </StackPanel>
                    </DataTemplate>
                </ItemsControl.ItemTemplate>
            </ItemsControl>

Can I somehow bind my properties to the textbloxk in the middle? Does not seem to be any intellisense. Thank you.

like image 579
user2915962 Avatar asked Nov 18 '14 15:11

user2915962


People also ask

How do I comment multiple lines in XAML?

Commenting out an entire XML block using CTRL+ / comments each line separately instead of creating a block comment. Select the entire block of xml and hit CTRL+/ to comment the entire block.

What is ForEach statement in C#?

The foreach statement executes a statement or a block of statements for each element in an instance of the type that implements the System.Collections.IEnumerable or System.Collections.Generic.IEnumerable<T> interface, as the following example shows: C# Copy. Run.

How do you write a ForEach loop in a list C#?

In the following example, we loop over a list with the forEach method. var words = new List<string> {"tea", "falcon", "book", "sky"}; words. ForEach(e => Console. WriteLine(e));


1 Answers

Foreach is achieved with a list view like ListBox, ListView, etc. the simplest form is the ItemsControl class (no scrolling, etc.). The list is passed to the view using the ItemsSource property. The repeated code block is usually defined in the ItemTemplate template.

Have a look at this answer: https://stackoverflow.com/a/3063208/876814

like image 154
Rico Suter Avatar answered Oct 16 '22 06:10

Rico Suter