Some days ago I realized that in Silverlight, in order to always update the bindings on any texbox (in order to validate for error in each KeyPress) I needed this code on TextChanged Event event in every TextBox I had in the system:
TextBox txCtl = (TextBox)sender; if (txCtl != null)
{
var be = txCtl.GetBindingExpression(TextBox.TextProperty);
if (be != null)
{
be.UpdateSource();
}
}
This code works pretty well (source: http://forums.silverlight.net/t/51100.aspx/1). The problem is: I don’t want to repeat it in every view CodeBehind I have, so I decided to make a custom ViewBase where I would leave this code on it. What I did was simply:
public class ViewBase : ChildWindow
{
protected void tboxTextChanged(object sender, TextChangedEventArgs e)
{
TextBox txCtl = (TextBox)sender; if (txCtl != null)
{
var be = txCtl.GetBindingExpression(TextBox.TextProperty);
if (be != null)
{
be.UpdateSource();
}
}
}
}
And then my view now is a ViewBase, instead of a UserControl, so I also changed the XAML to:
<src:ViewBase x:Class="Oi.SCPOBU.Silverlight.Pages.CadastroClassificacao"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:src="clr-namespace:Oi.SCPOBU.Silverlight.Pages" [...]
Finally, in my textbox I left the event referencing the same method as usual, but now the method is in ViewBase, istead of being in the CodeBehind:
<TextBox
x:Name="tbxNome"
Width="300"
MaxLength="50"
HorizontalAlignment="Left"
TextChanged="tboxTextChanged"
Text="{Binding DTOClassificacao.Nome, Mode=TwoWay, NotifyOnValidationError=True>
Seems pretty straightforward to me, but this doesn’t work. The code compiles, but in runtime I get the error: “Message=Failed to assign to property ‘System.Windows.Controls.TextBox.TextChanged’. [Line: 43 Position: 37]”, on the InitializeComponent() Method.
Anybody knows how can I assign a method from my base class to an event? Or will I really have to repeat this code in every single View I have?
Have you tried
UpdateSourceTrigger.PropertyChanged?