串口 WPF ComboBox 数据绑定

5
我希望能将可用的串口列表绑定到下拉框中。目前,我是手动添加可用的串口。就像这样:
            foreach (string s in SerialPort.GetPortNames())
        {
            ComboBoxItem cbi = new ComboBoxItem();
            cbi.Content = s;
            myComboBox.Items.Add(cbi);
        }

我的组合框名称是myComboBox。我应该怎么做绑定呢?谢谢。
1个回答

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>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接