Hello,
Welcome to Microsoft Q&A!
Currently, the ComboBox control doesn't contain a built-in method to sort its items. If you need to sort the items of the ComboBox, you will need to sort the item source of the ComboBox instead. The simplest way is to sort the source list with LINQ. Use the orderby
command of LINQ sentence to change the source list.
Here is a sample I made and you could take look at it.
Xaml:
<Grid>
<ComboBox x:Name="FontsCombo" Header="Fonts" Height="88" Width="296" DisplayMemberPath="Id"/>
</Grid>
Code-behind:
public sealed partial class MainPage : Page
{
public List<TestModel> source { get; set; }
public MainPage()
{
this.InitializeComponent();
source = new List<TestModel>();
this.Loaded += MainPage_Loaded;
}
private void MainPage_Loaded(object sender, RoutedEventArgs e)
{
for (int i = 0; i < 10; i++)
{
Random random = new Random();
int RandomNumber = random.Next(0, 100);
TestModel model = new TestModel { Id = RandomNumber};
source.Add(model);
}
// sort the source list by ID
var newSource= from item in source
orderby item.Id
select item;
FontsCombo.ItemsSource = newSource;
}
}
public class TestModel
{
public int Id { get; set; }
}
I generated 10 items with random numbers. Then I use the LINQ to get the newSource
as the source of the ComboBox.
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.