Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Binding multiple controls to the object selected in combobox

Tags:

c#

.net

binding

wpf

I have a student class as displayed below

public class Student
{
    public string Name { get; set; }
    public string Operator { get; set; }
    public IList<Subject> Subjects { get; set; }
}

Now I want to bind the collection of this student to the three controls of the my window as shown below

<ComboBox  Margin="12,28,0,0"
           Name="cbStudents"
           VerticalAlignment="Top"
           ItemsSource="{Binding Path=PersonList}"
           DisplayMemberPath="Name"
           SelectedValuePath="Operator" />
<TextBox  Margin="12,75,0,0"
          Name="tbOperator"
          VerticalAlignment="Top"
          Text="{Binding ElementName=cbStudents,Path=SelectedValue}" />
<ComboBox Margin="12,123,0,0"
          Name="cbSubjects"
          VerticalAlignment="Top"
          ItemsSource="{Binding ElementName=cbStudents, Path=SelectedValue}"
          DisplayMemberPath="SubjectName" />

Now here my concern is that whenever I change a selection in cbStudentsthen in that case other controls should also change their corresponding values also. Here as per the code given above whenever the selection in cbStudentschanges the text in the tbOperator is changing and the same I want to implement for cbSubjects also. Is there a way around for this apart from having a SelectionChanged event of cbStudents.

like image 482
Vikram Avatar asked Dec 06 '25 06:12

Vikram


1 Answers

You want that the TextBox tbOperator displays the Operator of the SelectedItem of your ComboBox cbStudents and that the other ComboBox contains the Subjects of the SelectedItem of your ComboBox cbStudents.

Then the following XAML should do what you want (removed unrelavant code to solve your problem):

<ComboBox Name="cbStudents" 
          ItemsSource="{Binding Path=PersonList}" 
          DisplayMemberPath="Name" />
<TextBox Name="tbOperator" 
         Text="{Binding SelectedItem.Operator, ElementName=cbStudents}" />
<ComboBox Name="cbSubjects" 
          ItemsSource="{Binding SelectedItem.Subjects, ElementName=cbStudents}" 
          DisplayMemberPath="SubjectName" />
like image 132
Jehof Avatar answered Dec 08 '25 19:12

Jehof