【发布时间】:2010-03-16 13:40:06
【问题描述】:
有没有办法在 Silverlight 中触发按键事件时触发双向数据绑定。目前我必须失去对文本框的关注才能触发绑定。
<TextBox x:Name="Filter" KeyUp="Filter_KeyUp" Text="{Binding Path=Filter, Mode=TwoWay }"/>
【问题讨论】:
标签: silverlight
有没有办法在 Silverlight 中触发按键事件时触发双向数据绑定。目前我必须失去对文本框的关注才能触发绑定。
<TextBox x:Name="Filter" KeyUp="Filter_KeyUp" Text="{Binding Path=Filter, Mode=TwoWay }"/>
【问题讨论】:
标签: silverlight
您还可以使用 Blend 交互行为来创建可重用的行为,以更新 KeyUp 上的绑定,例如:
public class TextBoxKeyUpUpdateBehaviour : Behavior<TextBox>
{
protected override void OnAttached()
{
base.OnAttached();
AssociatedObject.KeyUp += AssociatedObject_KeyUp;
}
void AssociatedObject_KeyUp(object sender, KeyEventArgs e)
{
var bindingExpression = AssociatedObject.GetBindingExpression(TextBox.TextProperty);
if (bindingExpression != null)
{
bindingExpression.UpdateSource();
}
}
protected override void OnDetaching()
{
base.OnDetaching();
AssociatedObject.KeyUp -= AssociatedObject_KeyUp;
}
}
【讨论】:
我通过这样做实现了这一点......
Filter.GetBindingExpression(TextBox.TextProperty).UpdateSource();
在 XAML 中
<TextBox x:Name="Filter" Text="{Binding Path=Filter, Mode=TwoWay, UpdateSourceTrigger=Explicit}" KeyUp="Filter_KeyUp"/>
【讨论】:
我们对我们的应用程序有相同的要求,但有些客户使用的是 MacO。 MacOs 并不总是触发 keyup 事件(至少在 Firefox 中)。
在接受的答案中,这成为一个大问题,因为 UpdateSourceTrigger 设置为 Explicit,但该事件永远不会触发。结果:您永远不会更新绑定。
但是,TextChanged 事件总是在触发。改为听这个,一切都很好:)
这是我的版本:
public class AutoUpdateTextBox : TextBox
{
public AutoUpdateTextBox()
{
TextChanged += OnTextChanged;
}
private void OnTextChanged(object sender, TextChangedEventArgs e)
{
this.UpdateBinding(TextProperty);
}
}
还有UpdateBinding ExtensionMethod:
public static void UpdateBinding(this FrameworkElement element,
DependencyProperty dependencyProperty)
{
var bindingExpression = element.GetBindingExpression(dependencyProperty);
if (bindingExpression != null)
bindingExpression.UpdateSource();
}
【讨论】: