【问题标题】:Populating a AutoCompleteBox with a list of anonymous types使用匿名类型列表填充 AutoCompleteBox
【发布时间】:2012-01-02 23:22:36
【问题描述】:

我正在为我的 WPF C# 项目进行用户选择 userControl。 我确实为选择做了一个自定义的自动完成控件,但出于优化目的,我现在正在研究使用 WPF 工具包中的自动完成文本框。

由于我在数据库中有成千上万的用户,我不想使用自定义类或我检索的列表中的许多 foreach。因此,考虑到这一点,这是我的问题。

var list = from cu in conn3.customer_users
select new  {
              username    =  cu.username,
             name        =  cu.fname.TrimEnd() + " " + cu.lname.TrimEnd()
                 // This would of course be built with more info from more entities. 

             };

            this.autoComplete.ItemsSource = list.ToList();

现在这里的问题是它为结果框输出以下格式(在搜索中)。

{ username = DEI1231 , name = Missy Anderson }

所以我不想 foreach 列表,而是在绑定它或制作列表时对其进行格式化。

有什么想法吗?

【问题讨论】:

  • 很抱歉离开了几天,但是是的!谢谢Parapura,它确实解决了一些问题。几个实验室小时,我想我现在已经很稳定了。谢谢。

标签: c# wcf linq autocomplete anonymous-types


【解决方案1】:

你的最终选择必须是字符串而不是匿名类型

 var str = from cu in x
           // your stuff
           select cu.username + cu.fname;

另一种选择是保留您的匿名类型并在绑定中使用StringFormat

<TextBlock >
    <TextBlock.Text>
        <MultiBinding StringFormat="{}{0}  {1}">
            <Binding ElementName="username" Path="Text"/>
            <Binding ElementName="name" Path="Text"/>
        </MultiBinding>
    </TextBlock.Text>
</TextBlock>

另一种选择是在匿名类型中设置一个包含您想要显示的完整字符串的字段,并使用 DisplayMemberPath 进行绑定

【讨论】:

    【解决方案2】:

    我不想在开头的空格上做更多的麻烦,最后决定只允许初始空格并最终从元字符串中删除所有空格。

    问题实际上是在它自身的事件中,所以这是由存在的解决方案。我不再对此进行任何研究,因为转而使用实际消息中的标签来代替元数据。并带有前缀。例如。 @元 让我们看看它是如何工作的;)

     private string metaInput { get; set; }
        public string MetaInput 
        {
            get
            {
                return metaInput;
            }
    
            set 
            {
                string x = value;
                if (x.Length > 3)
                {
                    if (x.EndsWith(" "))
                    {
    
                    string z = x.Replace(" ", "");
                    x = z.Replace(",", "");
                    int l = x.Length;
    
                        if (l > 2)
                        {
                            metaInput = null;
                            SaveMetaWord(x);
                        }
    
                        else 
                        {
                            metaInput = null;
                        }
                    }
    
                }
    
                else 
                {
                    metaInput = value;
                }
    
            }
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-03-27
      • 2011-09-05
      • 2011-05-18
      • 1970-01-01
      • 2018-10-16
      • 2013-07-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多