I have a Textbox which is bound to my data object. If the validation fails, I would like to show a popup which contains the error message. In XAML this works fine. I'm using the following XAML:
<TextBox Height="23" Margin="54,12,104,0" Name="textBox1"
VerticalAlignment="Top" Text="{Binding Value, ValidatesOnExceptions=True, UpdateSourceTrigger=PropertyChanged}"></TextBox>
<Popup Name="myPopup" PlacementTarget="{Binding ElementName=textBox1}"
IsOpen="{Binding ElementName=textBox1, Path=(Validation.HasError), Mode=OneWay}"
>
<TextBlock Name="myPopupText" Background="LightBlue" Foreground="Blue">
The value is invalid
</TextBlock>
</Popup>
My problem is that I have to create the popup and binding in code and I cannot get it to work. I have tried several different options. I also used dummy converter just to see whether the binding works at all. It seems that the binding works when I create it (it gets the initial value) but after that nothing happens. I can see that the Validation.HasError updates correctly (TextBox's border turns red), but that's it. My dummy converter is not called. Following is the code I'm using:
Popup popup = new Popup();
popup.Name = "somepopup";
// Source is the textbox which is bound to the data object
popup.PlacementTarget = source;
popup.Placement = PlacementMode.Bottom;
TextBlock txtblock = new TextBlock();
txtblock.Background = Brushes.LightBlue;
txtblock.Foreground = Brushes.Blue;
txtblock.Text = "this is the error message";
popup.Child = txtblock;
Binding is_open_binding = new Binding("(Validation.HasError)");
is_open_binding.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged;
is_open_binding.Source = source;
is_open_binding.Mode = BindingMode.OneWay;
is_open_binding.NotifyOnValidationError = true;
is_open_binding.ValidatesOnExceptions = true;
is_open_binding.Converter = new TempValueConverter();
popup.SetBinding(Popup.IsOpenProperty, is_open_binding);