views:

100

answers:

1

Basic problem: How do I bind a textbox to the selected item of a combobox who's itemsource is the result of a LINQ query on a WCF RIA Services Domain context.

Additional requirement: When the selected item is changed the binding should update. Additional requirement: The binding should be two way.

My solution so far:

After the user clicks to create a new item, new items are created and added to the object set but not persisted yet (one for each language). After that this code runs. The combobox is supposed to allow the user to select one of the created items, which is displayed as it's corresponding language. The bound textboxes should allow the user to edit the item.

Code behind:

//Setup the combobox
LanguageComboBox.ItemsSource = dc.GeneralStatistics.Where(g => g.RelatedResourceId.Equals(guid));
LanguageComboBox.DisplayMemberPath = "Language.LanguageName";
LanguageComboBox.SelectedItem = dc.GeneralStatistics.First(g => g.Language.LanguageName.Equals("English"));

//Setup the textboxes
this.StatisticsText.DataContext = (LanguageComboBox.SelectedItem as GeneralStatistics).Text;
this.ShortDescriptionText.DataContext = (LanguageComboBox.SelectedItem as GeneralStatistics).ShortDescription;

XAML CODE:

<ComboBox x:Name="LanguageComboBox" />
<TextBox x:Name="ShortDescriptionText" Text="{Binding}" />
<TextBox x:Name="StatisticsText" Text="{Binding}" />

The problem with my solution:

It does not work, because when I change the selection in the combobox the textboxes do not update. I could implement the selection changed event handler and manually update the textboxes, but that would defeat the purpose of binding the textboxes. What is the best practice here?

A: 

You can simplify the code by doing the following.

Code behind:

LanguageComboBox.DataContext = dc.GeneralStatistics.Where(g => g.RelatedResourceId.Equals(guid)); 

XAML:

<ComboBox x:Name="LanguageComboBox" /> 
<TextBox x:Name="ShortDescriptionText" Text="{Binding ElementName=LanguageComboBox, Path=SelectedItem.ShortDescription}" /> 
<TextBox x:Name="StatisticsText" Text="{Binding ElementName=LanguageComboBox, Path=SelectedItem.LongDescription}" /> 
W.Meints