UWP C# 如何附加 .json 文件并在组中识别它们

UWP C# How to append .json file and to identify them in groups

我正在尝试创建一个 usercontrol 来显示 windows 物联网核心上 json 文件中的项目组。

我有一个“创建组”按钮。按下后,它将创建 64 个 usercontrols 以及相应的详细信息并显示在 scrollviewer 中。随后,我可以编辑 64 个 usercontrol 中任何一个的单个项目,然后保存 json 文件。

我的 class usercontrol 如下;

我有一个问题,关于如何创建 64 个项目的 不同的组 并将所有附加到同一个 json 文件中,然后从选择中显示它们提到的不同的群体.

请帮忙谢谢

组Class

[DataContract]
public class DecoderGroup
{
    [DataMember]
    public int groupID{ get; set; }
    [DataMember]
    public string groupName{ get; set; }
    [DataMember]
    public int cardAddress { get; set; }
    [DataMember]
    public bool enabled { get; set; }
    [DataMember]
    public int z1label { get; set; }
    [DataMember]
    public int z2label { get; set; }
    [DataMember]
    public int z3label { get; set; }
    [DataMember]
    public int z4label { get; set; }
    [DataMember]
    public bool zone1 { get; set; }
    [DataMember]
    public bool zone2 { get; set; }
    [DataMember]
    public bool zone3 { get; set; }
    [DataMember]
    public bool zone4 { get; set; }
    [DataMember]
    public List<byte> txData { get; set; }

    public DecoderGroup(int id, int address, int z1, int z2, int z3, int z4)
    {
        groupName = "Group";
        zone1 = false;
        zone2 = false;
        zone3 = false;
        zone4 = false;

        z1label = z1;
        z2label = z2;
        z3label = z3;
        z4label = z4;
    }
}

MainPage.xaml.cs

private void AddGroup_Click(object sender, RoutedEventArgs e)
    {
        ZonesList_Panel.Children.Clear();

        int groupid = 1;
        int cardadr;

        for (cardadr = 1; cardadr <= MAXCARDS; cardadr++)
        {
            var z4 = (4 * cardadr);
            var z3 = (4 * cardadr) - 1;
            var z2 = (4 * cardadr) - 2;
            var z1 = (4 * cardadr) - 3;

            DecoderGroupUserControl decoderGroupControl = new DecoderGroupUserControl(this, new DecoderGroup(groupid, cardadr, z1, z2, z3, z4));
            ZonesList_Panel.Children.Add(decoderGroupControl);
        }
    }

private async void SaveGroup_Click(object sender, RoutedEventArgs e)
        {
                await saveGroupsToJSON(getGroups());
            
        }

public async Task saveGroupsToJSON(List<DecoderGroup> groups)
        {
            var serializer = new DataContractJsonSerializer(typeof(List<DecoderGroup>));
            using (var stream = await ApplicationData.Current.LocalFolder.OpenStreamForWriteAsync(DECODERGROUPS_FILE, CreationCollisionOption.OpenIfExists))
            {
                serializer.WriteObject(stream, groups);
            }
        }

    public List<DecoderGroup> getGroups()
    {
        List<DecoderGroup> ret = new List<DecoderGroup>();
        foreach (DecoderGroupUserControl u in ZonesList_Panel.Children)
        {
            //add condition for group ID
            ret.Add(u.decoderGroup);
        }
        return ret;
    }

用户控件

 public DecoderGroupUserControl(MainPage page, DecoderGroup group)
    {
        this.InitializeComponent();
        mainPage = page;
        this.decoderGroup = group;

        Z1Name.Text = group.z1label.ToString();
        Z2Name.Text = group.z2label.ToString();
        Z3Name.Text = group.z3label.ToString();
        Z4Name.Text = group.z4label.ToString();
    }

推荐使用UserControl作为ListView的DateTemplate,这样就不需要创建多个usercontrol再添加到页面中。然后你可以读取json个文件并将json个对象转换成一个集合,你可以将集合作为ListView的Itemsource。

通过实现 INotifyPropertyChanged 接口,TwoWay 数据绑定可以反映对集合的 UI 更改。最后,您可以将更改后的集合写入 json 文件。

请注意,您需要下载 Newtonsoft.Json 才能通过管理 NuGet 包解析 json 对象。请参考以下代码。

MyUserControl1.xaml:

<UserControl
   ..>
   <Grid>
       <!--customize the usercontrol style-->
        <StackPanel>
            <StackPanel Orientation="Horizontal" >
                <TextBox Margin="0,0,20,0"  Text="{Binding Name,Mode=TwoWay}" BorderThickness="0"/>
                <TextBox Text="{Binding Job,Mode=TwoWay}" BorderThickness="0"/>
            </StackPanel>
            <TextBox Text="{Binding Age,Mode=TwoWay}" BorderThickness="0"/>
        </StackPanel>
    </Grid>
</UserControl>

MainPage.xaml:

<Page..>

    <Grid>
        <StackPanel>
            <ListView ItemsSource="{x:Bind Results,Mode=TwoWay}">
            <ListView.ItemTemplate>
                <DataTemplate x:DataType="local:Person">
                    <local:MyUserControl1>                        
                    </local:MyUserControl1>
                </DataTemplate>
            </ListView.ItemTemplate>
        </ListView>
            <Button x:Name="SaveButton" Content="Save" Click="SaveButton_Click"/>
        </StackPanel>
    </Grid>
</Page>

MainPage.xaml.cs:

namespace WriteJson
{
    public sealed partial class MainPage : Page
    {
        public ObservableCollection<Person> Persons { get; set; }
        public ObservableCollection<Person> Results { get; set; }
        public string path;
        public MainPage()
        {
            this.InitializeComponent();
            CreateJsonFile();
            path = ApplicationData.Current.LocalFolder.Path + "\info.json";    
            Results = JsonConvert.DeserializeObject<ObservableCollection<Person>>(File.ReadAllText(path));
            Debug.WriteLine("bind successfully");
        }  
       public async void CreateJsonFile()
        {
            //check if info.json exists, if it doesn't exist, create it
            StorageFolder folder = ApplicationData.Current.LocalFolder;
            StorageFile file;
            try
            {            
                file = await folder.GetFileAsync("info.json");
            }
            catch
            {
                await folder.CreateFileAsync("info.json");
                Persons = new ObservableCollection<Person>()
            {
                new Person(){Name="tom",Job="teacher",Age=24},
                new Person(){Name="lily",Job="nurse",Age=20},
                new Person(){Name="ming",Job="student",Age=26},
                new Person(){Name="kiki",Job="lawyer",Age=28},
                new Person(){Name="jack",Job="worker",Age=21},
            };

                path = ApplicationData.Current.LocalFolder.Path + "\info.json";
                File.WriteAllText(path, JsonConvert.SerializeObject(Persons));
                Debug.WriteLine("create a json file successfully");
            }
          
        }
     
        private void SaveButton_Click(object sender, RoutedEventArgs e)
        {
            File.WriteAllText(path, JsonConvert.SerializeObject(Results));
            Debug.WriteLine("save successfully");
        }
    }
    public class Person:INotifyPropertyChanged
    {
       private string name;
        private string job;
        private int age;
        public string Name 
        { 
            get { return name; } 
            set 
            {
                name = value;
                RaisePropertyChanged("Name");
            } 
        }
        public string Job
        {
            get { return job; }
            set
            {
                job = value;
                RaisePropertyChanged("Job");
            }
        }
        public int Age
        {
            get { return age; }
            set
            {
                age = value;
                RaisePropertyChanged("Age");
            }
        }

        public event PropertyChangedEventHandler PropertyChanged;
        public void RaisePropertyChanged(string propertyname=null)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyname));
        }
    }
}