Home > front end >  Combobox Selected Items not binding correctly when using it with ItemsControl
Combobox Selected Items not binding correctly when using it with ItemsControl

Time:01-28

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:

    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?

CodePudding user response:

SelectedProperty must be defined as a public property:

 public string SelectedProperty { get; set; }

This is a public field:

public string SelectedProperty;

CodePudding user response:

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 }" />

  •  Tags:  
  • Related