WPF列表框显示属性绑定

时间:2016-12-19 12:37:04

标签: c# wpf xaml

我有一个WPF ListBox如下:

<ListBox x:Name="myListBox"  ItemsSource="{Binding}" Visibility="Visible" Width="Auto"  SelectionMode="Single"  HorizontalAlignment="Stretch" VerticalAlignment="Stretch" MinWidth="150">
</ListBox>

private ObservableCollection<MyClass> _myCollection;
private ListBox _listBox;

protected virtual void GetControls()
{
    object value;

    if ((value = GetTemplateChild("myListBox")) != null)
    {
        _listBox = value as ListBox;
        if (_listBox != null)
        {
            if (_listBox.ItemsSource == null)
                _listBox.ItemsSource = _myCollection;
        }
    }
}

private void LoadItems()
{
    List<MyClass> items = await GetAllItemsForDisplay();

    _myCollection.AddRange(verbs.AsParallel().OrderBy(v => v?.DisplayName));
}

这导致所有项目都列在列表框中,但显示文本为 My.NameSpace.MyCLass 。实际上我想显示MyClass的DisplayName属性。

我该怎么做?如何设置Display的值等于MyClass.DisplayName

1 个答案:

答案 0 :(得分:2)

在ListBox中设置DisplayMemberPath="DisplayName"

DisplayMemberPath

ItemTemplate