Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Serial port WPF ComboBox DataBinding

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.

like image 358
Syaiful Nizam Yahya Avatar asked Mar 19 '13 09:03

Syaiful Nizam Yahya


1 Answers

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>
like image 57
doerig Avatar answered Oct 20 '22 07:10

doerig