繁体   English   中英

XAML相当于一个foreach

[英]XAML equivalent of a foreach

好的,所以我试图将项目列表传递到XAML视图,以便“循环”它们。 我习惯使用html并且还没有真正理解如何在XAML中实现这一点。

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

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模板calles GroupDetailPage,它包含一个左侧的列表视图和一个中间的“详细视图”,根据我选择的列表中的哪个项目进行切换。 这是列表视图的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")

                }
            }
        }

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

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

 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吗? 似乎没有任何intellisense。 谢谢。

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM