XAML equivalent of a foreach

本文关键字:foreach of equivalent XAML | 更新日期: 2023-09-27 18:31:01

好的,所以我正在尝试将项目列表传递到 XAML 视图中以"循环"它们。我习惯于 html 工作,并没有真正了解如何在 XAML 中实现这一点。

这是包含 Item 的类,也是一个创建我希望传递给视图的 Item 列表的方法:

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;
        } 
    }

我的视图由一个 XAML 模板调用 GroupDetailsPage 组成,该视图由左侧的列表视图和中间的"详细信息视图"组成,该视图应该根据我从列表中选择的项进行切换。下面是列表视图的 XAML,保持不变:

 <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>

下面是视图的代码隐藏。我想我需要在这里创建一个方法来获取我的项目列表并将其绑定到视图? 我一直在为此苦苦挣扎。我可能会陷入我的 MVC 思维中,以便能够弄清楚如何做到这一点:

  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")
                }
            }
        }

有人可以在这里把我引向正确的方向吗?我试图将我的项目列表传递给视图,并希望有一个等效的 foreach 循环或类似的东西?谢谢!

编辑:在 GroupDetailsPage 的构造函数中,我添加了以下代码:

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

这是否意味着我可以访问我的观点?

我从链接中添加了这段代码:

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

我可以以某种方式将我的属性绑定到中间的textbloxk吗?似乎没有任何智力。谢谢。

XAML equivalent of a foreach

Foreach 是通过 ListBoxListView 等列表视图实现的,最简单的形式是 ItemsControl 类(无滚动等)。该列表使用 ItemsSource 属性传递到视图。重复的代码块通常在ItemTemplate模板中定义。

看看这个答案:https://stackoverflow.com/a/3063208/876814