XAML相当于一个foreach

时间:2014-11-18 15:59:33

标签: c# xaml

好的,所以我试图将项目列表传递到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")

                }
            }
        }

有人可以在这里朝着正确的方向发展。我试图将我的项目列表传递给视图,并希望有一个等效的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。谢谢。

1 个答案:

答案 0 :(得分:7)

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

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