Combobox绑定源

时间:2013-08-20 11:52:24

标签: c# wpf serial-port

我有下面的wpf窗口:

     <Window x:Class="WpfApplication1.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 x:Key="portNames"
                            MethodName="GetPortNames"
                            ObjectType="{x:Type ports:SerialPort}" />
    </Window.Resources>
    <ComboBox Name="cbox" ItemsSource="{Binding Source={StaticResource portNames}}" SelectionChanged="ComboBox_SelectionChanged" />

</Window>

我使用ObjectDataProvider填充Com Port组合框。 但我不知道如何填充其他组合框。 使用C#函数:

 private void LoadBaudRates()
        {
            cboxBaudRate.DataContext = new int[] { 9600, 14400, 19200, 38400, 57600, 115200, 128000 };
            cboxBaudRate.SelectedIndex = 0;
        }
        private void LoadParity()
        {
            cboxParity.DataContext = Enum.GetValues(typeof(Parity));
        }
        private void LoadFlowControl()
        {
            cboxFlowControl.DataContext = Enum.GetValues(typeof(Handshake));
        }
        private void LoadCOMPorts()
        {
            var comPorts = SerialPort.GetPortNames();
            //cboxCOMPorts.DataContext = comPorts;
            this.cboxCOMPorts.DataContext = comPorts;
        }

1 个答案:

答案 0 :(得分:0)

如果您想在XAML中填充其他ComboBoxes,那么对于Enum,您也可以像创建COM端口一样创建ObjectDataProvider

<ObjectDataProvider x:Key="HandshakeValues" MethodName="GetValues" ObjectType="{x:Type sys:Enum}">
   <ObjectDataProvider.MethodParameters>
      <x:Type TypeName="ports:Handshake" />
   </ObjectDataProvider.MethodParameters>
</ObjectDataProvider>

<ComboBox ItemsSource="{Binding Source={StaticResource HandshakeValues}}"/>

对于int数组,您可以执行以下操作:

<ComboBox>
   <ComboBox.ItemsSource>
      <x:Array Type="{x:Type sys:Int32}">
         <sys:Int32>9600</sys:Int32>
         <sys:Int32>14400</sys:Int32>
         <sys:Int32>19200</sys:Int32>
         <sys:Int32>38400</sys:Int32>
         <sys:Int32>57600</sys:Int32>
         <sys:Int32>115200</sys:Int32>
         <sys:Int32>128000</sys:Int32>
      </x:Array>
   </ComboBox.ItemsSource>
</ComboBox>

其中sysxmlns:sys="clr-namespace:System;assembly=mscorlib"

相关问题