在WPF中向ComboBox添加文本和值

时间:2019-04-10 16:17:54

标签: wpf vb.net winforms

我从以下链接中获得了 WinForm 代码:http://net-informations.com/q/faq/combovalue.html

Public Class Form1
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    Dim comboSource As New Dictionary(Of String, String)()
    comboSource.Add("1", "Sunday")
    comboSource.Add("2", "Monday")
    comboSource.Add("3", "Tuesday")
    comboSource.Add("4", "Wednesday")
    comboSource.Add("5", "Thursday")
    comboSource.Add("6", "Friday")
    comboSource.Add("7", "Saturday")
    ComboBox1.DataSource = New BindingSource(comboSource, Nothing)
    ComboBox1.DisplayMember = "Value"
    ComboBox1.ValueMember = "Key"
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    Dim key As String = DirectCast(ComboBox1.SelectedItem, KeyValuePair(Of String, String)).Key
    Dim value As String = DirectCast(ComboBox1.SelectedItem, KeyValuePair(Of String, String)).Value
    MessageBox.Show(key & "   " & value)
End Sub
End Class

我试图将上述 WinForm 代码转换为如下所示的 WPF 代码。

xaml

<Window x:Class="MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<StackPanel>
    <Button x:Name="Button1" Height="25" Width="100" Content="Click Me"/>
    <ComboBox x:Name="ComboBox1" Height="25" Width="200"/>
</StackPanel>
</Window>

后面的代码

Class MainWindow
Private Sub MainWindow_Loaded(sender As Object, e As RoutedEventArgs) Handles Me.Loaded
    Dim comboSource As New Dictionary(Of String, String)()
    comboSource.Add("1", "Sunday")
    comboSource.Add("2", "Monday")
    comboSource.Add("3", "Tuesday")
    comboSource.Add("4", "Wednesday")
    comboSource.Add("5", "Thursday")
    comboSource.Add("6", "Friday")
    comboSource.Add("7", "Saturday")
    ComboBox1.DataSource = New BindingSource(comboSource, Nothing)
    ComboBox1.DisplayMember = "Value"
    ComboBox1.ValueMember = "Key"
End Sub
Private Sub Button1_Click(sender As Object, e As RoutedEventArgs) Handles Button1.Click
    Dim key As String = DirectCast(ComboBox1.SelectedItem, KeyValuePair(Of String, String)).Key
    Dim value As String = DirectCast(ComboBox1.SelectedItem, KeyValuePair(Of String, String)).Value
    MessageBox.Show(key & "   " & value)
End Sub
End Class

但是您在这张图片中看到了一些错误:https://prnt.sc/na5iie

那么,我该如何解决这些错误?

1 个答案:

答案 0 :(得分:1)

使用WPF,我们使用ItemsSource而不是DataSource设置ComboBox源项目列表,其工作方式略有不同。

每个项目都可以是您要使用的任何对象,请记住该对象本身就是您的ValueMember。在您的情况下,默认情况下,使用字典将为每个项目提供类似“ [[1,Sunday]”的外观,因为该项目的类型为KeyValuePair(Of String, String)

要按照自己的喜好设置样式,最简单的方法是使用XAML模板,例如:

<ComboBox ItemsSource="{Binding comboSource}">
    <ComboBox.ItemTemplate>
        <DataTemplate>
            <Label Content="{Binding Value}"/>
        </DataTemplate>
    </ComboBox.ItemTemplate>
</ComboBox>

然后,组合框的SelectedItem将是KeyValuePair,因此当您需要按预期在其他地方使用所选项目时,只需使用其Key