C # WPF ComboBox ItemTemplate с DisplayMemberPath - PullRequest
0 голосов
/ 03 октября 2019

Я хочу создать ComboBox с пользовательскими элементами (каждый элемент принадлежит списку людей).

Проблема в том, что при выборе элемента появляется имя класса модели «Персона».

Я хотел бы, чтобы имя человека отображалось при выборе элемента.

public class Person
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string Surname { get; set; }
        public int Age { get; set; }

        public string NameAndSurname
        {
            get
            {
                return $"{Name} {Surname}";
            }
        }
    }
<ComboBox x:Name="ComboBox" Style="{StaticResource MaterialDesignFloatingHintComboBox}" materialDesign:HintAssist.Hint="Serach" IsEditable="True">
    <ComboBox.ItemTemplate>
        <DataTemplate>
            <StackPanel Orientation="Horizontal">
                <TextBlock FontWeight="Bold" Text="{Binding NameAndSurname}"/>
                <TextBlock FontWeight="Bold" Text="{Binding Age}"/>
            </StackPanel>
        </DataTemplate>
    </ComboBox.ItemTemplate>
</ComboBox>

1 Ответ

0 голосов
/ 03 октября 2019

Это кажется немного неполным. Вам не хватает вашего ItemsSource для самого Combobox, DataContext, и ваша модель представления должна состоять из коллекции. Вот реализация, которую я только что ввел и проверил с помощью Visual Studio 2019:

Для MainWindow.xaml

<Window x:Class="WpfAppForSEQuestion.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:WpfAppForSEQuestion"
        DataContext="{Binding Source={x:Static local:ViewModel.The}}"
        Title="MainWindow" Height="450" Width="800">

    <Grid>
        <ComboBox HorizontalAlignment="Center" ItemsSource="{Binding Persons}" VerticalAlignment="Center">
            <ComboBox.ItemTemplate>
                <DataTemplate>
                    <StackPanel Orientation="Horizontal">
                        <TextBlock FontWeight="Bold" Text="{Binding NameAndSurname}"/>
                        <TextBlock FontWeight="Bold" Margin="10,0,0,0" Text="{Binding Age}"/>
                    </StackPanel>
                </DataTemplate>
            </ComboBox.ItemTemplate>
        </ComboBox>
    </Grid>
</Window>

и вот (тривиальный) пример вашей модели представления:

using System.Collections.ObjectModel;

namespace WpfAppForSEQuestion
{
    public class Person
    {
        public Person( string name, string surname, int age )
        {
            Id = 93;
            Name = name;
            Surname = surname;
            Age = age;
        }

        public int Id { get; set; }
        public string Name { get; set; }
        public string Surname { get; set; }
        public int Age { get; set; }

        public string NameAndSurname
        {
            get
            {
                return $"{Name} {Surname}";
            }
        }

   public override string ToString()
    {
        return NameAndSurname;
    }
     }

    public class ViewModel
    {
        public ViewModel()
        {
            Persons = new ObservableCollection<Person>();
            Persons.Add( new Person( "James", "Hurst", 60 ) );
            Persons.Add( new Person( "Virginia", "Hurst", 90 ) );
            Persons.Add( new Person( "Oscar", "Hurst", 100 ) );
        }

        /// <summary>
        /// Get the (singleton) instance of this view-model.
        /// </summary>
        public static ViewModel The
        {
            get
            {
                if (_instance == null)
                {
                    _instance = new ViewModel();
                }
                return _instance;
            }
        }
        /// <summary>
        /// This is the one, singleton instance of this class.
        /// </summary>
        private static ViewModel _instance;

        public ObservableCollection<Person> Persons { get; set; }
    }
}
...