TextBox
上的默认数据绑定(bind)是TwoWay
,只有当 TextBox
失去焦点时,它才会将文本提交给属性。
当我按下 TextBox
上的 Enter 键时,是否有任何简单的 XAML 方法可以进行数据绑定(bind)?我知道这在后面的代码中很容易做到,但想象一下如果这个 TextBox
是在一些复杂的 DataTemplate
中。
最佳答案
您可以通过创建 attached behaviour 使自己成为一个纯 XAML 方法.
像这样:
public static class InputBindingsManager
{
public static readonly DependencyProperty UpdatePropertySourceWhenEnterPressedProperty = DependencyProperty.RegisterAttached(
"UpdatePropertySourceWhenEnterPressed", typeof(DependencyProperty), typeof(InputBindingsManager), new PropertyMetadata(null, OnUpdatePropertySourceWhenEnterPressedPropertyChanged));
static InputBindingsManager()
{
}
public static void SetUpdatePropertySourceWhenEnterPressed(DependencyObject dp, DependencyProperty value)
{
dp.SetValue(UpdatePropertySourceWhenEnterPressedProperty, value);
}
public static DependencyProperty GetUpdatePropertySourceWhenEnterPressed(DependencyObject dp)
{
return (DependencyProperty)dp.GetValue(UpdatePropertySourceWhenEnterPressedProperty);
}
private static void OnUpdatePropertySourceWhenEnterPressedPropertyChanged(DependencyObject dp, DependencyPropertyChangedEventArgs e)
{
UIElement element = dp as UIElement;
if (element == null)
{
return;
}
if (e.OldValue != null)
{
element.PreviewKeyDown -= HandlePreviewKeyDown;
}
if (e.NewValue != null)
{
element.PreviewKeyDown += new KeyEventHandler(HandlePreviewKeyDown);
}
}
static void HandlePreviewKeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.Enter)
{
DoUpdateSource(e.Source);
}
}
static void DoUpdateSource(object source)
{
DependencyProperty property =
GetUpdatePropertySourceWhenEnterPressed(source as DependencyObject);
if (property == null)
{
return;
}
UIElement elt = source as UIElement;
if (elt == null)
{
return;
}
BindingExpression binding = BindingOperations.GetBindingExpression(elt, property);
if (binding != null)
{
binding.UpdateSource();
}
}
}
然后在您的 XAML 中,将 InputBindingsManager.UpdatePropertySourceWhenEnterPressedProperty
属性设置为您希望在按下 Enter 键时更新的属性。像这样
<TextBox Name="itemNameTextBox"
Text="{Binding Path=ItemName, UpdateSourceTrigger=PropertyChanged}"
b:InputBindingsManager.UpdatePropertySourceWhenEnterPressed="TextBox.Text"/>
(您只需确保在 XAML 文件的根元素中包含“b”的 xmlns clr-命名空间引用,指向您将 InputBindingsManager 放入的命名空间。
关于c# - 在按下 Enter 键时绑定(bind) TextBox,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/563195/