views:

65

answers:

0

I am experiencing a weird problem. I have a WPF form into which I insert a UserControl which presents the user with a view of what they are currently doing.

So I set MyControl.ViewObject = SomeCompositeObjectInstance, and then add MyControl into my form to make it visible.

SomeCompositeObjectInstance has a property of another class type which has a few properties. As this is used in various places I wrote a UserControl for editing the child type and reused it in numerous places.

The UserControl for the main composite instance implements INotifyPropertyChanged, as does the child class it owns. These events are being triggered correctly, with the correct property names.

So....

When I set MyControl.ViewObject = SomeCompositeObjectInstance I see the main control's UI updated correctly, and the embedded control showing the correct data for the child object.

I remove the main control from the form, change the MyControl.ViewObject to another main composite object, and then insert it back into the form for display (I don't want to go into why I remove/add).

The bindings in the main control for the parent class are all updated correctly, the DataContextChanged event is fired on the embedded control with the new data context - but the embedded control has all of its control's bindings still bound to the other instance's child object.

In my main control...

The ViewDto.Name is updated, but the StringRegexValidatorControl doesn't update its UI controls even though the DataContextChanged even fires.

I found the following is a work-around...

     void SetTextBoxBinding(TextBox textBox, string path)
 {
  textBox.DataContext = DataContext;
  var binding = BindingOperations.GetBindingExpression(textBox, TextBox.TextProperty);
  BindingOperations.ClearBinding(textBox, TextBox.TextProperty);
  BindingOperations.SetBinding(textBox, TextBox.TextProperty, new Binding(path));
 }

 void SetCheckBoxBinding(CheckBox checkBox, string path)
 {
  checkBox.DataContext = DataContext;
  var binding = BindingOperations.GetBindingExpression(checkBox, CheckBox.IsCheckedProperty);
  BindingOperations.ClearBinding(RegularExpressionTextBox, CheckBox.IsCheckedProperty);
  BindingOperations.SetBinding(RegularExpressionTextBox, CheckBox.IsCheckedProperty, new Binding(path));
 }

 private void UserControl_DataContextChanged(object sender, DependencyPropertyChangedEventArgs e)
 {
  EditStringRegexValidatorDto newObject = DataContext as EditStringRegexValidatorDto;
  if (newObject != null)
  {
   SetTextBoxBinding(MinimumLengthTextBox, "MinimumLength");
   SetTextBoxBinding(MaximumLengthTextBox, "MaximumLength");
   SetTextBoxBinding(RegularExpressionTextBox, "RegularExpression");
   SetCheckBoxBinding(AllowEmptyCheckBox, "AllowEmpty");
  }
 }

But that really should be unnecessary. Checking the properties of "binding" reveals that the DataItem is still the old DataContext. Can anyone think why the bindings are not getting a new DataItem?