D
D
Dmytro2017-11-04 14:32:08
WPF
Dmytro, 2017-11-04 14:32:08

How to bind a collection to a ComboBox?

Hello, there is an "Owner" class in a WPF application

public class Owner : INotifyPropertyChanged
    {
        private string _name; // имя владельца

        public event PropertyChangedEventHandler PropertyChanged;

        public Owner(string name)
        {
            _name = name;
        }

        public Owner()
        {
            _name = "Анон";
        }

        public string Name
        {
            get => _name;
            set
            {
                _name = value;
                OnPropertyChanged();
            }
        } // Name

        public void OnPropertyChanged([CallerMemberName]string prop = "")
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(prop));
        }

        public override string ToString()
        {
            return $"{_name}";
        }
    }

59fda5888c749314618499.png
In the ViewModel class of the MVVM pattern, I create an ObservableCollection of owners and pass it to the xaml markup in the view
<ListBox Grid.Row="1" Grid.Column="2" ItemsSource="{Binding Owners}">
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <StackPanel Margin="5">
                        <TextBlock FontSize="18" Text="{Binding Path=Name}" />
                    </StackPanel>
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>

The ListBox is displayed successfully, there is no problem.
But I need a dropdown list:
<ComboBox Margin="5 5 5 0" 
                      ItemsSource="{Binding Owners}"
                      DisplayMemberPath="Name"
                      Text = "{Binding Owner, UpdateSourceTrigger = PropertyChanged}" />

59fda596e730f745074163.png
...whose content is simply missing after compilation.
PS The Owners collection is initialized and populated with data.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
Roman, 2017-11-04
@yarosroman

<ComboBox Margin="5 5 5 0" 
                      ItemsSource="{Binding Owners}"
                      DisplayMemberPath="Name"
                      Text = "{Binding Owner, UpdateSourceTrigger = PropertyChanged}" />

Text = "{Binding Owner, UpdateSourceTrigger = PropertyChanged}" This is not necessary. Add SelectedValuePath and SelectedValue, in your case it will be "Name"

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question