Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/295.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/haskell/10.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 将可观察集合绑定到GridView_C#_Uwp_Observablecollection_Uwp Xaml - Fatal编程技术网

C# 将可观察集合绑定到GridView

C# 将可观察集合绑定到GridView,c#,uwp,observablecollection,uwp-xaml,C#,Uwp,Observablecollection,Uwp Xaml,我的UWP需要有一个收藏夹页面,允许用户在页面上重新排序和保存数据。最初,我的数据来自一个大型JSON文件,该文件使用Newtonsoft的JSON.net进行反序列化,并存储在一个字典中,然后填充公共ObservableCollection 这就是我现在迷路的地方,将ObservableCollection设置为DataContext,然后在XAML代码中使用数据作为绑定,用每个项目所需的所有标题、副标题和图像填充GridView。 理论上,这应该是可行的,但在我的测试和测试中,页面仍然是空白

我的UWP需要有一个收藏夹页面,允许用户在页面上重新排序和保存数据。最初,我的数据来自一个大型JSON文件,该文件使用Newtonsoft的JSON.net进行反序列化,并存储在一个字典中,然后填充公共ObservableCollection

这就是我现在迷路的地方,将ObservableCollection设置为DataContext,然后在XAML代码中使用数据作为绑定,用每个项目所需的所有标题、副标题和图像填充GridView。 理论上,这应该是可行的,但在我的测试和测试中,页面仍然是空白的,而所有幕后的C#代码似乎都应该填充

我不知道为什么这一页没有被填满,我要求助于你们所有人的集体帮助

附言:我真的不在乎这个代码的整洁,我只是想让它工作起来


XAML文件

<Page
x:Name="pageRoot"
x:Class="Melbourne_Getaway.FavouritesPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:Melbourne_Getaway"
xmlns:data="using:Melbourne_Getaway.Data"
xmlns:common="using:Melbourne_Getaway.Common"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d">

<Page.Resources>
    <x:String x:Key="AppName">Favourites</x:String>
</Page.Resources>

<!--
    This grid acts as a root panel for the page that defines two rows:
    * Row 0 contains the back button and page title
    * Row 1 contains the rest of the page layout
-->
<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
    <Grid.ChildrenTransitions>
        <TransitionCollection>
            <EntranceThemeTransition />
        </TransitionCollection>
    </Grid.ChildrenTransitions>
    <Grid.RowDefinitions>
        <RowDefinition Height="140" />
        <RowDefinition Height="*" />
    </Grid.RowDefinitions>

    <GridView
        x:Name="itemGridView"
        AutomationProperties.AutomationId="ItemsGridView"
        AutomationProperties.Name="Items"
        TabIndex="1"
        Grid.RowSpan="2"
        Padding="60,136,116,46"
        SelectionMode="None"
        IsSwipeEnabled="false"
        CanReorderItems="True"
        CanDragItems="True"
        AllowDrop="True"
        ItemsSource="{Binding Items}">
        <GridView.ItemTemplate>
            <DataTemplate>
                <Grid HorizontalAlignment="Left" Width="250" Height="107">
                    <Border Background="{ThemeResource ListViewItemPlaceholderBackgroundThemeBrush}">
                        <Image Source="{Binding ImagePath}" Stretch="UniformToFill" AutomationProperties.Name="{Binding Title}" />
                    </Border>
                    <StackPanel VerticalAlignment="Bottom" Background="{ThemeResource ListViewItemOverlayBackgroundThemeBrush}">
                        <TextBlock Text="{Binding Title}" Foreground="{ThemeResource ListViewItemOverlayForegroundThemeBrush}" Style="{StaticResource BaseTextBlockStyle}" Height="30" Margin="15,0,15,0" FontWeight="SemiBold" />
                        <TextBlock Text="{Binding Group}" Foreground="{ThemeResource ListViewItemOverlaySecondaryForegroundThemeBrush}" Style="{StaticResource BaseTextBlockStyle}" TextWrapping="NoWrap" Margin="15,-15,15,10" FontSize="12" />
                    </StackPanel>
                </Grid>
            </DataTemplate>
        </GridView.ItemTemplate>
    </GridView>

    <!-- Back button and page title -->
    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="120" />
            <ColumnDefinition Width="*" />
        </Grid.ColumnDefinitions>
        <Button x:Name="backButton" Margin="39,59,39,0" Command="{Binding NavigationHelper.GoBackCommand, ElementName=pageRoot}"
                    Style="{StaticResource NavigationBackButtonNormalStyle}"
                    VerticalAlignment="Top"
                    AutomationProperties.Name="Back"
                    AutomationProperties.AutomationId="BackButton"
                    AutomationProperties.ItemType="Navigation Button" />
        <TextBlock x:Name="pageTitle" Text="{StaticResource AppName}" Style="{StaticResource HeaderTextBlockStyle}" Grid.Column="1"
                    IsHitTestVisible="false" TextWrapping="NoWrap" VerticalAlignment="Bottom" Margin="0,0,30,40" />
    </Grid>
</Grid>
using Melbourne_Getaway.Common;
using Melbourne_Getaway.Data;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using Windows.Storage;
using Windows.UI.Popups;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Navigation;

namespace Melbourne_Getaway
{
    public sealed partial class FavouritesPage : Page
    {
        public ObservableCollection<ItemData> Items { get; set; }

        private ObservableDictionary defaultViewModel = new ObservableDictionary();
        private NavigationHelper navigationHelper;
        private RootObject jsonLines;
        private StorageFile fileFavourites;
        private Dictionary<string, ItemData> ItemData = new Dictionary<string, ItemData>();

        public FavouritesPage()
        {
            loadJson();
            getFavFile();

            this.InitializeComponent();
            this.navigationHelper = new NavigationHelper(this);
            this.navigationHelper.LoadState += navigationHelper_LoadState;
        }

        private void setupObservableCollection()
        {
            Items = new ObservableCollection<ItemData>(ItemData.Values);
            DataContext = Items;
        }

        private async void loadJson()
        {
            var file = await StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///DataModel/SampleData.json"));
            string lines = await FileIO.ReadTextAsync(file);
            jsonLines = JsonConvert.DeserializeObject<RootObject>(lines);
            feedItems();
        }

        private async void getFavFile()
        {
            Windows.Storage.StorageFolder storageFolder = Windows.Storage.ApplicationData.Current.LocalFolder;
            fileFavourites = await storageFolder.GetFileAsync("MelbGetaway.fav");
        }

        private async void feedItems()
        {
            if (await FileIO.ReadTextAsync(fileFavourites) != "")
            {
                foreach (var line in await FileIO.ReadLinesAsync(fileFavourites))
                {
                    foreach (var Group in jsonLines.Groups)
                    {
                        foreach (var Item in Group.Items)
                        {
                            if (Item.UniqueId == line)
                            {
                                var storage = new ItemData()
                                {
                                    Title = Item.Title,
                                    UniqueID = Item.UniqueId,
                                    ImagePath = Item.ImagePath,
                                    Group = Group.Title
                                };
                                ItemData.Add(storage.UniqueID, storage);
                            }
                        }
                    }
                }
            }
            else
            {//should only execute if favourites file is empty, first time use?
                foreach (var Group in jsonLines.Groups)
                {
                    foreach (var Item in Group.Items)
                    {
                        var storage = new ItemData()
                        {
                            Title = Item.Title,
                            UniqueID = Item.UniqueId,
                            ImagePath = Item.ImagePath,
                            Group = Group.Title
                        };
                        ItemData.Add(storage.UniqueID, storage);
                        await FileIO.AppendTextAsync(fileFavourites, Item.UniqueId + "\r\n");
                    }
                }
            }
            setupObservableCollection();
        }

        public ObservableDictionary DefaultViewModel
        {
            get { return this.defaultViewModel; }
        }

        #region NavigationHelper loader

        public NavigationHelper NavigationHelper
        {
            get { return this.navigationHelper; }
        }

        private async void MessageBox(string Message)
        {
            MessageDialog dialog = new MessageDialog(Message);
            await dialog.ShowAsync();
        }

        private async void navigationHelper_LoadState(object sender, LoadStateEventArgs e)
        {
            var sampleDataGroups = await SampleDataSource.GetGroupsAsync();
            this.defaultViewModel["Groups"] = sampleDataGroups;
        }

        #endregion NavigationHelper loader

        #region NavigationHelper registration

        protected override void OnNavigatedFrom(NavigationEventArgs e)
        {
            navigationHelper.OnNavigatedFrom(e);
        }

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            navigationHelper.OnNavigatedTo(e);
        }

        #endregion NavigationHelper registration
    }

    public class ItemData
    {
        public string UniqueID { get; set; }
        public string Title { get; set; }
        public string Group { get; set; }
        public string ImagePath { get; set; }
    }
}

宠儿


CS文件

<Page
x:Name="pageRoot"
x:Class="Melbourne_Getaway.FavouritesPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:Melbourne_Getaway"
xmlns:data="using:Melbourne_Getaway.Data"
xmlns:common="using:Melbourne_Getaway.Common"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d">

<Page.Resources>
    <x:String x:Key="AppName">Favourites</x:String>
</Page.Resources>

<!--
    This grid acts as a root panel for the page that defines two rows:
    * Row 0 contains the back button and page title
    * Row 1 contains the rest of the page layout
-->
<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
    <Grid.ChildrenTransitions>
        <TransitionCollection>
            <EntranceThemeTransition />
        </TransitionCollection>
    </Grid.ChildrenTransitions>
    <Grid.RowDefinitions>
        <RowDefinition Height="140" />
        <RowDefinition Height="*" />
    </Grid.RowDefinitions>

    <GridView
        x:Name="itemGridView"
        AutomationProperties.AutomationId="ItemsGridView"
        AutomationProperties.Name="Items"
        TabIndex="1"
        Grid.RowSpan="2"
        Padding="60,136,116,46"
        SelectionMode="None"
        IsSwipeEnabled="false"
        CanReorderItems="True"
        CanDragItems="True"
        AllowDrop="True"
        ItemsSource="{Binding Items}">
        <GridView.ItemTemplate>
            <DataTemplate>
                <Grid HorizontalAlignment="Left" Width="250" Height="107">
                    <Border Background="{ThemeResource ListViewItemPlaceholderBackgroundThemeBrush}">
                        <Image Source="{Binding ImagePath}" Stretch="UniformToFill" AutomationProperties.Name="{Binding Title}" />
                    </Border>
                    <StackPanel VerticalAlignment="Bottom" Background="{ThemeResource ListViewItemOverlayBackgroundThemeBrush}">
                        <TextBlock Text="{Binding Title}" Foreground="{ThemeResource ListViewItemOverlayForegroundThemeBrush}" Style="{StaticResource BaseTextBlockStyle}" Height="30" Margin="15,0,15,0" FontWeight="SemiBold" />
                        <TextBlock Text="{Binding Group}" Foreground="{ThemeResource ListViewItemOverlaySecondaryForegroundThemeBrush}" Style="{StaticResource BaseTextBlockStyle}" TextWrapping="NoWrap" Margin="15,-15,15,10" FontSize="12" />
                    </StackPanel>
                </Grid>
            </DataTemplate>
        </GridView.ItemTemplate>
    </GridView>

    <!-- Back button and page title -->
    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="120" />
            <ColumnDefinition Width="*" />
        </Grid.ColumnDefinitions>
        <Button x:Name="backButton" Margin="39,59,39,0" Command="{Binding NavigationHelper.GoBackCommand, ElementName=pageRoot}"
                    Style="{StaticResource NavigationBackButtonNormalStyle}"
                    VerticalAlignment="Top"
                    AutomationProperties.Name="Back"
                    AutomationProperties.AutomationId="BackButton"
                    AutomationProperties.ItemType="Navigation Button" />
        <TextBlock x:Name="pageTitle" Text="{StaticResource AppName}" Style="{StaticResource HeaderTextBlockStyle}" Grid.Column="1"
                    IsHitTestVisible="false" TextWrapping="NoWrap" VerticalAlignment="Bottom" Margin="0,0,30,40" />
    </Grid>
</Grid>
using Melbourne_Getaway.Common;
using Melbourne_Getaway.Data;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using Windows.Storage;
using Windows.UI.Popups;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Navigation;

namespace Melbourne_Getaway
{
    public sealed partial class FavouritesPage : Page
    {
        public ObservableCollection<ItemData> Items { get; set; }

        private ObservableDictionary defaultViewModel = new ObservableDictionary();
        private NavigationHelper navigationHelper;
        private RootObject jsonLines;
        private StorageFile fileFavourites;
        private Dictionary<string, ItemData> ItemData = new Dictionary<string, ItemData>();

        public FavouritesPage()
        {
            loadJson();
            getFavFile();

            this.InitializeComponent();
            this.navigationHelper = new NavigationHelper(this);
            this.navigationHelper.LoadState += navigationHelper_LoadState;
        }

        private void setupObservableCollection()
        {
            Items = new ObservableCollection<ItemData>(ItemData.Values);
            DataContext = Items;
        }

        private async void loadJson()
        {
            var file = await StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///DataModel/SampleData.json"));
            string lines = await FileIO.ReadTextAsync(file);
            jsonLines = JsonConvert.DeserializeObject<RootObject>(lines);
            feedItems();
        }

        private async void getFavFile()
        {
            Windows.Storage.StorageFolder storageFolder = Windows.Storage.ApplicationData.Current.LocalFolder;
            fileFavourites = await storageFolder.GetFileAsync("MelbGetaway.fav");
        }

        private async void feedItems()
        {
            if (await FileIO.ReadTextAsync(fileFavourites) != "")
            {
                foreach (var line in await FileIO.ReadLinesAsync(fileFavourites))
                {
                    foreach (var Group in jsonLines.Groups)
                    {
                        foreach (var Item in Group.Items)
                        {
                            if (Item.UniqueId == line)
                            {
                                var storage = new ItemData()
                                {
                                    Title = Item.Title,
                                    UniqueID = Item.UniqueId,
                                    ImagePath = Item.ImagePath,
                                    Group = Group.Title
                                };
                                ItemData.Add(storage.UniqueID, storage);
                            }
                        }
                    }
                }
            }
            else
            {//should only execute if favourites file is empty, first time use?
                foreach (var Group in jsonLines.Groups)
                {
                    foreach (var Item in Group.Items)
                    {
                        var storage = new ItemData()
                        {
                            Title = Item.Title,
                            UniqueID = Item.UniqueId,
                            ImagePath = Item.ImagePath,
                            Group = Group.Title
                        };
                        ItemData.Add(storage.UniqueID, storage);
                        await FileIO.AppendTextAsync(fileFavourites, Item.UniqueId + "\r\n");
                    }
                }
            }
            setupObservableCollection();
        }

        public ObservableDictionary DefaultViewModel
        {
            get { return this.defaultViewModel; }
        }

        #region NavigationHelper loader

        public NavigationHelper NavigationHelper
        {
            get { return this.navigationHelper; }
        }

        private async void MessageBox(string Message)
        {
            MessageDialog dialog = new MessageDialog(Message);
            await dialog.ShowAsync();
        }

        private async void navigationHelper_LoadState(object sender, LoadStateEventArgs e)
        {
            var sampleDataGroups = await SampleDataSource.GetGroupsAsync();
            this.defaultViewModel["Groups"] = sampleDataGroups;
        }

        #endregion NavigationHelper loader

        #region NavigationHelper registration

        protected override void OnNavigatedFrom(NavigationEventArgs e)
        {
            navigationHelper.OnNavigatedFrom(e);
        }

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            navigationHelper.OnNavigatedTo(e);
        }

        #endregion NavigationHelper registration
    }

    public class ItemData
    {
        public string UniqueID { get; set; }
        public string Title { get; set; }
        public string Group { get; set; }
        public string ImagePath { get; set; }
    }
}
使用Melbourne_Getaway.Common;
使用墨尔本大学Getaway.Data;
使用Newtonsoft.Json;
使用制度;
使用System.Collections.Generic;
使用System.Collections.ObjectModel;
使用Windows.Storage;
使用Windows.UI.Popups;
使用Windows.UI.Xaml.Controls;
使用Windows.UI.Xaml.Navigation;
墨尔本之旅
{
公共密封部分类收藏夹页面:第页
{
公共ObservableCollection项{get;set;}
private observedictionary defaultViewModel=new observedictionary();
私人导航助手导航助手;
私有rootobjectjsonline;
私有存储文件收藏夹;
私有字典ItemData=新字典();
公众喜爱
{
loadJson();
getFavFile();
this.InitializeComponent();
this.navigationHelper=新的navigationHelper(this);
this.navigationHelper.LoadState+=navigationHelper\u LoadState;
}
私有void setupObservableCollection()
{
Items=新的ObservableCollection(ItemData.Values);
DataContext=项目;
}
私有异步void loadJson()
{
var file=wait-StorageFile.getfilefromApplicationUrisync(新Uri(“ms”)-appx:///DataModel/SampleData.json"));
字符串行=等待文件IO.ReadTextAsync(文件);
jsonLines=JsonConvert.DeserializeObject(行);
饲料项目();
}
私有异步void getFavFile()
{
Windows.Storage.StorageFolder StorageFolder=Windows.Storage.ApplicationData.Current.LocalFolder;
filefavorities=wait-storageFolder.GetFileAsync(“MelbGetaway.fav”);
}
专用异步void feedItems()
{
如果(等待文件IO.ReadTextAsync(文件收藏夹)!=“”)
{
foreach(wait FileIO.ReadLinesAsync(filefavorites)中的var行)
{
foreach(jsonLines.Groups中的var组)
{
foreach(Group.Items中的变量项)
{
如果(Item.UniqueId==行)
{
var storage=newitemdata()
{
标题=项目。标题,
UniqueID=Item.UniqueID,
ImagePath=Item.ImagePath,
组=组。标题
};
ItemData.Add(storage.UniqueID,storage);
}
}
}
}
}
其他的
{//仅当收藏夹文件为空时才应执行,是否首次使用?
foreach(jsonLines.Groups中的var组)
{
foreach(Group.Items中的变量项)
{
var storage=newitemdata()
{
标题=项目。标题,
UniqueID=Item.UniqueID,
ImagePath=Item.ImagePath,
组=组。标题
};
ItemData.Add(storage.UniqueID,storage);
等待FileIO.AppendTextAsync(FileFavorites,Item.UniqueId+“\r\n”);
}
}
}
setupobserveCollection();
}
公共可观测默认视图模型
{
获取{返回this.defaultViewModel;}
}
#区域导航辅助加载程序
公共导航帮助器导航帮助器
{
获取{返回this.navigationHelper;}
}
专用异步void消息框(字符串消息)
{
MessageDialog=新建MessageDialog(消息);
wait dialog.ShowAsync();
}
私有异步void navigationHelper\u LoadState(对象发送方,LoadStateEventArgs e)
{
var sampleDataGroups=await SampleDataSource.GetGroupsAsync();
this.defaultViewModel[“Groups”]=sampleDataGroups;
}
#endregion NavigationHelper加载程序
#区域导航助手注册
受保护的覆盖无效OnNavigatedFrom(NavigationEventArgs e)
{
navigationHelper.OnNavigatedFrom(e);
}
受保护的