Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Combobox Selected Items not binding correctly when using it with ItemsControl

I need to bind the selected item to a property, but somehow it’s not working.

Here’s my attempt:

            <ItemsControl ItemsSource="{Binding MyItems}">
                <ItemsControl.ItemTemplate>
                    <DataTemplate>
                        <StackPanel>
                            <Label Content="{Binding FirstProperty}"/>
                            <ComboBox ItemsSource="{Binding SecondProperties}" SelectedItem="{Binding SelectedProperty}" />
...

Here is the model that does this:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

    private List<MyItems> _myItems;
    public List<MyItem> MyItems{
        get => _myItems;
        set
        {
            _myItems= value;
            OnPropertyChanged();
        }
    }

And here is my class:

public class MyProperty
{
    public List<string> SecondProperties{ get; set; }
    public string FirstProperty;
    public string SelectedProperty;
}

I want that the SelectedProperty matches what I selected. When I use it later, FirstProperty is fine, the combobox list SecondProperties is also fine, but SelectedProperty is always null.

Any help?

>Solution :

I fixed your code:

public class MyProperty : INotifyPropertyChanged
{
    private string selectedProperty;
     public string SelectedProperty
    {
        get 
        { 
            return selectedProperty; 
        }
        set 
        { 
            selectedProperty = value;
            OnPropertyChanged("SelectedProperty");}
        } 

 protected virtual void OnPropertyChanged(string propertyName)
 {
     if (PropertyChanged != null)
     {
         PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
     }
 }

Add Mode=TwoWay in your xaml

<ComboBox ItemsSource="{Binding SecondProperties}" SelectedItem="{Binding SelectedProperty,  Mode=TwoWay }" />

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading