polfosol polfosol - 4 months ago 24
C# Question

Change the text style of a ComboBox item in a dynamic ComboBox

I have a ComboBox in my form displaying the list of available COM ports. Here is the code I wrote:

[XAML]

<Window x:Class="test1.MainWindow" x:Name="cbtest1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="200" Width="200">
<Grid>
<StackPanel Margin="40">
<ComboBox x:Name="com_ports" ItemsSource="{Binding PortsList}"/>
</StackPanel>
</Grid>
</Window>


And the code behind

using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Windows;
using System.Windows.Controls;

namespace test1
{
public partial class MainWindow : Window
{
public MainWindow()
{
var ports = new List<string>(System.IO.Ports.SerialPort.GetPortNames());
var cb = new ObservableCollection<ComboBoxItem>();
foreach (var x in ports)
{
cb.Add(new ComboBoxItem { Content = x });
var p = new System.IO.Ports.SerialPort(x);
if (p.IsOpen)
{
// Bold that item in the combobox
}
}
PortsList = cb;
this.DataContext = this;
InitializeComponent();
}
public ObservableCollection<ComboBoxItem> PortsList { get; set; }
}
}


Now, as I have commented in the code, I want the ComboBox to display the open ports in bold. I have no idea what to do. I searched for a while on the SO and google, but had no luck. I appreciate if someone simply explains this to me -a WPF/C# noob.

Answer

The easiest change would be

        foreach (var x in ports)
        {
            var addMe = new ComboBoxItem { Content = x };
            cb.Add(addMe);
            var p = new System.IO.Ports.SerialPort(x);
            if (p.IsOpen)
            {
                addMe.FontWeight = FontWeights.Bold;
            }
        }