在 View 上分配事件时无法引用基类方法



几天前,我意识到在Silverlight中,为了始终更新任何texbox上的绑定(以便验证每个KeyPress中的错误),我需要在系统中的每个TextBox中的TextChanged Event事件上使用以下代码:

TextBox txCtl = (TextBox)sender; if (txCtl != null)
{
var be = txCtl.GetBindingExpression(TextBox.TextProperty);
if (be != null)
{
be.UpdateSource();
}
}

这段代码运行得很好(来源:http://forums.silverlight.net/t/51100.aspx/1)。问题是:我不想在CodeBehind的每个视图中重复它,所以我决定制作一个自定义的ViewBase,把这个代码留在上面

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();
}
}
}
}

然后我的视图现在是ViewBase,而不是UserControl,所以我还将XAML更改为:

<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" [...]

最后,在我的文本框中,我留下了引用与往常相同方法的事件,但现在该方法在ViewBase中,而不是在CodeBehind:中

<TextBox
x:Name="tbxNome"
Width="300"
MaxLength="50"
HorizontalAlignment="Left"
TextChanged="tboxTextChanged"
Text="{Binding DTOClassificacao.Nome, Mode=TwoWay, NotifyOnValidationError=True>

对我来说似乎很简单,但这行不通。代码已编译,但在运行时,我在InitializeComponent()方法上收到错误:"Message=未能分配给属性System.Windows.Controls.TextBox.TextChanged'.[Line:43 Position:37]"。

有人知道我如何将基类中的方法分配给事件吗?或者我真的必须在我拥有的每个视图中重复这个代码吗?

以便始终更新任何texbox上的绑定(以便验证每个KeyPress中的错误)我需要TextChanged上的这段代码我在系统中的每个TextBox中的事件

您尝试过UpdateSourceTrigger.PropertyChanged吗?

<TextBox Text="{Binding Text, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>

最新更新