2013-03-19 44 views
2

我想將可用串口列表綁定到ComboBox。目前,我手動添加可用的串口。像這樣,串口WPF ComboBox DataBinding

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

myComboBox是我的組合框名稱。我該如何做綁定?謝謝。

回答

10

您可以使用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>