串口WPF ComboBox DataBinding

Sya*_*hya 4 data-binding wpf combobox

我想将可用串行端口的列表绑定到ComboBox.目前,我手动添加可用的串口.像这样,

            foreach (string s in SerialPort.GetPortNames())
        {
            ComboBoxItem cbi = new ComboBoxItem();
            cbi.Content = s;
            myComboBox.Items.Add(cbi);
        }
Run Code Online (Sandbox Code Playgroud)

myComboBox是我的组合框名称.我该怎么做绑定?谢谢.

doe*_*rig 13

您可以使用ObjectDataProvider绑定到方法.

<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>
Run Code Online (Sandbox Code Playgroud)