【问题标题】:How to bind custom object data to a ComboBox如何将自定义对象数据绑定到 ComboBox
【发布时间】:2009-02-02 14:50:40
【问题描述】:

我有一个自定义类Contact

我正在尝试将 List<Contact> 绑定到 ComboBox。

但我无法为 Windows.Resources 部分获取正确的语法/命令,例如下面的代码给出了错误“类型引用找不到名为'List'的公共类型”,我需要在Windows.Resources 中修复什么才能使其正常工作?

XAML:

<Window x:Class="dpwpf.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Window1" Height="300" Width="300"
    xmlns:system="clr-namespace:System;assembly=mscorlib"
    xmlns:local="clr-namespace:dpwpf">

    <Window.Resources>
        <ObjectDataProvider
            x:Key="contacts"
            MethodName="GetContacts"
            ObjectType="{x:Type system:List}">
            <ObjectDataProvider.MethodParameters>
                <x:Type TypeName="local:GetContacts"/>
            </ObjectDataProvider.MethodParameters>
        </ObjectDataProvider>
    </Window.Resources>


    <StackPanel>
        <StackPanel>
            <TextBlock Text="Select the contact:"/>
            <ComboBox ItemsSource="{Binding
                Source={StaticResource contacts}}"/>
        </StackPanel>
    </StackPanel>
</Window>

类背后的代码:

namespace dpwpf
{
    class StoreDB
    {
        private string connectionString = "App_Data/main.sqlite";

        public List<Contact> GetContacts()
        {
            SQLiteConnection conn = new SQLiteConnection("Data Source=" + connectionString);
            SQLiteCommand cmd = conn.CreateCommand();

            List<Contact> contacts = new List<Contact>();
            try
            {
                conn.Open();
                cmd.CommandText = String.Format("SELECT * FROM contacts");
                SQLiteDataReader reader = cmd.ExecuteReader();
                while (reader.Read())
                {
                    Contact contact = new Contact(
                        Int32.Parse(reader[0].ToString()),
                        reader[1].ToString(),
                        reader[2].ToString()
                    );
                    contacts.Add(contact);
                }
            }
            finally
            {
                conn.Close();
            }

            return contacts;
        }
    }
}

【问题讨论】:

    标签: wpf xaml data-binding combobox


    【解决方案1】:

    你的问题出在这一行:

    ObjectType="{x:Type system:List}"
    

    这需要是定义GetContacts 的对象。

    在您的 window1.xaml.cs 中,它看起来像这样:

    ObjectType="{x:Type X:Window1}"
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-07-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多