amirm
amirm

Reputation: 41

Bind wpf textbox to selectedItem of listBox

I have two classes

Class A
{
     public int something { get; set; }
     public B classB = new B();
}


Class B
{
     public int anotherThing { get; set; }
}

I have ObservableCollection from Class A

public ObservableCollection<A> listOfClasses = new ObservableCollection<A>();

Now, I have listbox that is binded to listOfClasses

                    <ListBox x:Name="justAList" SelectionMode="Extended">
                        <ListBox.ItemContainerStyle>
                            <Style TargetType="{x:Type ListBoxItem}">
                                <Setter Property="Content" Value="{Binding Path=something}"></Setter>
                            </Style>
                        </ListBox.ItemContainerStyle>
                    </ListBox>

And of course the binding.

justAList.ItemsSource = listOfClasses ;

So far everything works. I'm able to see the list with its items (I'm adding the items to the list with some other method). My question is, I want to have another textbox and bind it to the anotherThing int in Class B. How can it be done?

Upvotes: 0

Views: 2397

Answers (1)

Rohit Vats
Rohit Vats

Reputation: 81233

First of all you need to make an instance of class B a property in case you want binding support:

private B classB = new B();
public B ClassB
{
   get
   {
      return classB;
   }
   set
   {
      classB = value;
   }
}

And now you can bind to TextBox like this:

<TextBox Text="{Binding ClassB.anotherThing}"/>

Make sure TextBox DataContext is set to some instance of ClassA.

UPDATE

As mentioned in comments you want to bind TextBox Text with SelectedItem instance, which can be achieved this way:

<TextBox Text="{Binding ElementName=justAList, 
                        Path=SelectedItem.ClassB.anotherThing}"/>

Upvotes: 1

Related Questions