Data binding auto update question

杨岑 121 Reputation points
2024-04-18T02:13:17.27+00:00

I cannot get it working. I bind a list of FileCategory to a ComboBox.ItemsSource (OneWay mode), but when I add new items to the list, the ComboBox won't get update accordingly.

class FileCategory
{
    public string Name { get; set; }
    public string Description { get; set; }
}

internal IList<FileCategory> Categories = new List<FileCategory>
{
        new FileCategory { Name = "aaa", Description = "aaa item" },
        new FileCategory { Name = "bbb", Description = "bbb item" },
        new FileCategory { Name = "ccc", Description = "ccc item" },
};

private void Button_Click(object sender, RoutedEventArgs e)
{
    var name = "new#" + Categories.Count;
    Categories.Add(new FileCategory { Name = name, Description = name + " item" });
}

Categories.Add(new FileCategory { Name = name, Description = name + " item" });
<ComboBox x:Name="combo1"
          ItemsSource="{x:Bind Categories, Mode=OneWay}"
          SelectedValuePath="Name">
Universal Windows Platform (UWP)
0 comments No comments
{count} votes

Accepted answer
  1. Junjie Zhu - MSFT 15,056 Reputation points Microsoft Vendor
    2024-04-18T04:14:01.2833333+00:00

    Hi @杨岑 ,

    Welcome to Microsoft Q&A!

    It is recomended to use ObservableCollection, it provides notifications when items get added or removed, or when the whole list is refreshed.

       ObservableCollection<FileCategory> Categories = new ObservableCollection<FileCategory>
       {
           new FileCategory { Name = "aaa", Description = "aaa item" },
           new FileCategory { Name = "bbb", Description = "bbb item" },
           new FileCategory { Name = "ccc", Description = "ccc item" },
       };
    
    

    Thank you.


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments

0 additional answers

Sort by: Most helpful