使用匿名类型列表填充AutoCompleteBox

4
我正在为我的WPF C#项目制作用户选择用户控件。我曾经为选择制作了一个自定义的自动完成控件,但出于优化目的,现在我正在研究使用WPF Toolkit中的自动完成文本框。
由于我的数据库中有成千上万的用户,我不想使用自定义类或在检索列表时使用太多的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 }
所以我不想遍历列表,而是想在绑定或创建列表时进行格式化。
有什么想法吗?

抱歉离开了几天,但是没错!谢谢Parapura,它确实解决了一些问题。经过几个小时的实验,我现在认为我已经掌握了它。谢谢。 - Per Svensson
2个回答

2
你最终选择的必须是字符串,而不是匿名类型。
 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进行绑定。

-1

我不想再为开头的空格烦恼了,最终决定只允许初始空格,并最终从元字符串中剥离所有空格。

实际上问题出在事件本身,所以这是我的解决方案。我不会再深入研究这个问题,因为我将把标签放在实际消息内部的元数据中。并带有前缀。例如:@meta。让我们看看它的效果 ;)

 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;
            }

        }
    }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接