将数据绑定到ComboBox

时间:2016-05-26 15:24:37

标签: vb.net combobox windows-phone-8.1

我遇到了绑定数据到ComboBox的障碍。我正在开发Windows Phone 8.1中的应用程序,我想要做的就是在ComboBox中列出打印机。

这是我的XAML:

<ComboBox x:Name="cbxPrinters" 
          HorizontalAlignment="Left"
          Margin="153,150,0,0" 
          VerticalAlignment="Top" 
          Width="237">
    <ComboBox.ItemTemplate>
        <DataTemplate>
            <StackPanel Orientation="Vertical" Margin="2">
                <TextBlock Text="{Binding Name}"></TextBlock>
            </StackPanel>
        </DataTemplate>
    </ComboBox.ItemTemplate>
</ComboBox>

这是填充列表的类。数据以Id|Name|Id|Name|Id|Name etc的形式返回,这就是SplitFor[...]Next语句的原因。这段代码确实填充了类并将它们添加到列表中。最后,我留下了54个打印机列表:

Public Class Printer

Public Id As Integer
Public Name As String

Public Function Populate(ByVal ResultString As String) As List(Of Printer)

    Dim _Results As List(Of String) = ResultString.Split(New String("|")).ToList

    Dim _Printers As New List(Of Printer)

    If _Results.Count >= 2 Then

        For i = 0 To _Results.Count - 1 Step 2
            Dim _Printer As New Printer

            With _Printer
                .Id = _Results(i)
                .Name = _Results(i + 1).Trim()
            End With

            _Printers.Add(_Printer)
        Next
    End If

    Return _Printers

End Function

End Class

这段代码将List(Of Printer)分配给ComboBox

Protected Overrides Async Sub OnNavigatedTo(e As NavigationEventArgs)

    _Printer = New Printer

    _Printers = _Printer.Populate(Await GetPrinterList())

    If _Printers.Count > 0 Then
        cbxPrinters.ItemsSource = _Printers
    End If

End Sub

当我启动应用程序并进入此页面时,代码运行正常,但我还剩下54个空白选项可供选择。

1 个答案:

答案 0 :(得分:0)

Zaggler的帮助下,在调查堆栈跟踪之后:

  

错误:BindingExpression路径错误:'COACH_HOUSE_SCAN_APP.Printer,COACH HOUSE SCAN APP,Version = 1.0.0.0,Culture = neutral,PublicKeyToken = null'找不到'Id'属性。

我稍微更改了这个类,以便IdName现在是Properties

Public Property Id As Integer
Public Property Name As String

我按照Zaggler的建议设置了DisplayMemberPathSelectedValuePath

Protected Overrides Async Sub OnNavigatedTo(e As NavigationEventArgs)

    _Printer = New Printer

    _Printers = _Printer.Populate(Await GetPrinterList())

    If _Printers.Count > 0 Then
        cbxPrinters.ItemsSource = _Printers
        cbxPrinters.DisplayMemberPath = "Id"
        cbxPrinters.SelectedValuePath = "Name"
    End If

End Sub

我也删除了XAML的这一部分:

<ComboBox.ItemTemplate>
    <DataTemplate>
        <StackPanel Orientation="Vertical" Margin="2">
            <TextBlock Text="{Binding Name}"></TextBlock>
        </StackPanel>
    </DataTemplate>
</ComboBox.ItemTemplate>

让XMAL看起来像这样:

<ComboBox x:Name="cbxPrinters" 
      HorizontalAlignment="Left"
      Margin="153,150,0,0" 
      VerticalAlignment="Top" 
      Width="237">
</ComboBox>

这解决了我的问题,现在打印机现已列在ComboBox