Search code examples
c#jsonxamluwpwindows-iot-core-10

UWP C# Bind JSON items to Button MenuFlyout


i have a dynamic list of client devices which will be added over the network. Once they are connected their details are save in JSON file. I would like to have an additional display and control of the client device(s) where I click on a Add button with a MenuFlyout populated with the list of the client device(s)'s ClientName from the JSON file. Once the menuitem is selected, it will add a button and connection status indicator (eg. connected, disconnected or error) for the respective client device selected on a grid. This is what I have did for adding the button but couldn't figure out how to bind to the JSON

Please help. Thanks.

my json class is created in a separate .cs json file I am not sure did I do it correctly at MenuFlyoutItem_Click where item.clientname has an error.

The json file clientslist.txt i have checked for the format it seems correct. The JSON file

enter image description here

enter image description here


Solution

  • You can refer to following code. I have not found a way with using Binding or x:Bind,but we can add the MenuFlyoutItem to the MenuFlyout manually after the json data deserialized.

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            var deviceList = JsonConvert.DeserializeObject<List<DeviceInfo>>(jsonData);
            var menuFlyout = new MenuFlyout();
            foreach (var device in deviceList)
            {
                var menuFlyoutItem = new MenuFlyoutItem() { Name = device.DeviceName, Text = device.DeviceName };
                menuFlyoutItem.Tag = device.DeviceName;
                menuFlyoutItem.Click += MenuFlyoutItem_Click;
                menuFlyout.Items.Add(menuFlyoutItem);
            }
    
            ButtonCreateDevice.Flyout = menuFlyout;
        }
    
        private void MenuFlyoutItem_Click(object sender, RoutedEventArgs e)
        {
            var item = sender as MenuFlyoutItem;
            var deviceName = item.DeviceName;
    
            //TO DO SOMETHING
        }
    

    DeviceInfo class defined as:

        class DeviceInfo
        {
            public string DeviceName { get; set; }
            public string Status { get; set; };
        }
    

    Tested with the sample data(jsonData) as:

    [{"DeviceName":"LED-1","Status":"Connected"},{"DeviceName":"LED-2","Status":"Connected"},{"DeviceName":"LED-3","Status":"Connected"}]
    

    enter image description here