我正在使用 .net 4.5,在一个 WPF 项目中。我想要触发一个文本框的TextChangedEvent事件。以下是我的做法:
tb.RaiseEvent(new RoutedEventArgs(TextBox.TextChangedEvent));
我之前在Button.ClickEvent上做过相同类型的RaiseEvent操作,如何做这个?
这会产生以下错误:
异常:抛出:“类型为'System.Windows.RoutedEventArgs'的对象无法转换为类型'System.Windows.Controls.TextChangedEventArgs'。”(System.ArgumentException)抛出了一个System.ArgumentException:“类型为'System.Windows.RoutedEventArgs'的对象无法转换为类型'System.Windows.Controls.TextChangedEventArgs'。”
[编辑]
实际文本框文本更改是通过附加行为处理的,如下所示。我想在另一个控件的附加行为中以编程方式引发事件的地方。在后面的行为中,我确实有文本框对象。
public class textboxTextChangedBehavior : Behavior<TextBox>
{
protected override void OnAttached()
{
base.OnAttached();
AssociatedObject.TextChanged += OnTextChanged;
}
protected override void OnDetaching()
{
AssociatedObject.TextChanged -= OnTextChanged;
base.OnDetaching();
}
private void OnTextChanged(object sender, TextChangedEventArgs args)
{
var textBox = (sender as TextBox);
if (textBox != null)
{
//Populate ObservableCollection
}
}
}
我尝试发起事件的地方:
public class FindPopupBehavior : Behavior<Popup>
{
protected override void OnAttached()
{
AssociatedObject.Opened += _OpenFindPopup;
}
protected override void OnDetaching()
{
AssociatedObject.Opened -= _OpenFindPopup;
}
void _OpenFindPopup(object sender, EventArgs e)
{
//Fake a TextBox text changed event
if (TextBoxObject == null)
return;
TextBox tb = TextBoxObject as TextBox;
if (tb.Text == "")
return;
tb.RaiseEvent(new RoutedEventArgs(TextBox.TextChangedEvent));
}
public static readonly DependencyProperty TextBoxProperty =
DependencyProperty.Register("TextBoxObject", typeof(TextBox), typeof(FindPopupBehavior), new UIPropertyMetadata(null));
public object TextBoxObject
{
get { return (object)GetValue(TextBoxProperty); }
set { SetValue(TextBoxProperty, value); }
}
}
[编辑2]
该文本框位于弹出窗口中。当此弹出窗口关闭时,ObservableCollection会被清除,但文本框的文本仍然存在,只是被隐藏了。如果重新打开弹出窗口并且文本框中有文本,它需要重新填充ObservableCollection。它在textchanged行为中执行此操作。这就是为什么我考虑模拟事件的原因。