简体   繁体   English

C#中的ComboBox成员路径

[英]ComboBox member path in c#

I have a function in my WPF project that connects to mySQL database and fetches all the information in the table Clients. 我的WPF项目中有一个函数,该函数连接到mySQL数据库并获取表Clients中的所有信息。

I'm creating a binding list of type client which will have as a value the client ID and as a display the Client Name. 我正在创建一个类型为client的绑定列表,该列表将具有一个值,即客户端ID并作为客户端名称的显示。

Is there any easy way to set the display member path to the two columns, the name and number of the client concatenated together directly and easily, without the need of much more code? 是否有任何简单的方法可以将显示成员路径设置为两列,即客户端的名称和编号直接轻松地连接在一起,而无需更多代码? As in without the need to create a table and add a column which joins these two fields together, and set the display to be the new columns name. 与之类似,无需创建表并添加将这两个字段连接在一起的列,并将显示设置为新的列名称。

public void GetClientsList()
    {
    BindingList<client> Clients = new BindingList<client>();

    try
    {
        using (smsdbmsEntities context = new smsdbmsEntities())
        {
            var query = (from r in context.clients.AsEnumerable()
                         select r).ToList();

            foreach (var x in query)
            {
                Clients.Add(x);
            }

            cb_ClientList.ItemsSource = Clients;

            cb_ClientList.DisplayMemberPath = "Name";
            cb_ClientList.SelectedValuePath = "CID";
        }
    }
    catch (Exception ex)
    {
        MessageBox.Show("Cannot get Clients! " + ex.ToString());
    }
}

Try the following (use NotMapped attribute so you don't have to create a column in database if its your model class). 尝试以下操作(使用NotMapped属性,因此如果模型类是数据库的列,则不必在数据库中创建列)。

[NotMapped]
public string ClientInfo
{
    get { return string.Format("{0} {1}", Name, NumberOfClients); }
}

Bind ClientInfo as your DisplayMemberPath property. 将ClientInfo绑定为DisplayMemberPath属性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM