I want to bind list of available Serial Port to a ComboBox. Currently, Im adding available serial port manually. Like so,
foreach (string s in SerialPort.GetPortNames())
{
ComboBoxItem cbi = new ComboBoxItem();
cbi.Content = s;
myComboBox.Items.Add(cbi);
}
myComboBox is my combobox name. How can i do the binding? Thanks.
You can use an ObjectDataProvider to bind to a method.
<Window x:Class="SerialPortBinding.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:ports="clr-namespace:System.IO.Ports;assembly=System"
Title="MainWindow" SizeToContent="WidthAndHeight">
<Window.Resources>
<ObjectDataProvider ObjectType="{x:Type ports:SerialPort}" MethodName="GetPortNames" x:Key="portNames"/>
</Window.Resources>
<ComboBox ItemsSource="{Binding Source={StaticResource portNames}}"/>
</Window>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With