"UpdateSourceTrigger = PropertyChanged" эквивалент для Windows Phone 7 TextBox
Есть ли способ получить TextBox в Windows Phone 7 для обновления привязки, поскольку пользователь вводит каждую букву, а не после потери фокуса?
Как и в следующем WPF TextBox:
<TextBox Text="{Binding Path=TextProperty, UpdateSourceTrigger=PropertyChanged}"/>
Ответы
Ответ 1
Silverlight для WP7 не поддерживает указанный вами синтаксис. Вместо этого сделайте следующее:
<TextBox TextChanged="OnTextBoxTextChanged"
Text="{Binding MyText, Mode=TwoWay,
UpdateSourceTrigger=Explicit}" />
UpdateSourceTrigger = Explicit
- отличный бонус здесь. Что это такое? Явно: Обновляет источник привязки только при вызове метода UpdateSource
. Он сохраняет один дополнительный набор привязок, когда пользователь покидает TextBox
.
В С#:
private void OnTextBoxTextChanged( object sender, TextChangedEventArgs e )
{
TextBox textBox = sender as TextBox;
// Update the binding source
BindingExpression bindingExpr = textBox.GetBindingExpression( TextBox.TextProperty );
bindingExpr.UpdateSource();
}
Ответ 2
Мне нравится использовать прикрепленное свойство. На всякий случай вы попадаете в этих маленьких педерастов.
<toolkit:DataField Label="Name">
<TextBox Text="{Binding Product.Name, Mode=TwoWay}" c:BindingUtility.UpdateSourceOnChange="True"/>
</toolkit:DataField>
И затем код поддержки.
public class BindingUtility
{
public static bool GetUpdateSourceOnChange(DependencyObject d)
{
return (bool)d.GetValue(UpdateSourceOnChangeProperty);
}
public static void SetUpdateSourceOnChange(DependencyObject d, bool value)
{
d.SetValue(UpdateSourceOnChangeProperty, value);
}
// Using a DependencyProperty as the backing store for …
public static readonly DependencyProperty
UpdateSourceOnChangeProperty =
DependencyProperty.RegisterAttached(
"UpdateSourceOnChange",
typeof(bool),
typeof(BindingUtility),
new PropertyMetadata(false, OnPropertyChanged));
private static void OnPropertyChanged (DependencyObject d,
DependencyPropertyChangedEventArgs e)
{
var textBox = d as TextBox;
if (textBox == null)
return;
if ((bool)e.NewValue)
{
textBox.TextChanged += OnTextChanged;
}
else
{
textBox.TextChanged -= OnTextChanged;
}
}
static void OnTextChanged(object s, TextChangedEventArgs e)
{
var textBox = s as TextBox;
if (textBox == null)
return;
var bindingExpression = textBox.GetBindingExpression(TextBox.TextProperty);
if (bindingExpression != null)
{
bindingExpression.UpdateSource();
}
}
}
Ответ 3
Не через синтаксис привязки, нет, но это достаточно легко. Вы должны обработать событие TextChanged и вызвать UpdateSource для привязки.
private void TextBox_TextChanged(object sender, TextChangedEventArgs e)
{
((TextBox) sender).GetBindingExpression( TextBox.TextProperty ).UpdateSource();
}
Это можно легко преобразовать в прикрепленное поведение.
Ответ 4
В вызове события TextChanged UpdateSource().
BindingExpression be = itemNameTextBox.GetBindingExpression(TextBox.TextProperty);
be.UpdateSource();
Ответ 5
Вы можете написать свое собственное поведение TextBox для обработки Update on TextChanged:
Это мой пример в PasswordBox, но вы можете просто изменить его для обработки любого свойства любого объекта.
public class UpdateSourceOnPasswordChangedBehavior
: Behavior<PasswordBox>
{
protected override void OnAttached()
{
base.OnAttached();
AssociatedObject.PasswordChanged += OnPasswordChanged;
}
protected override void OnDetaching()
{
base.OnDetaching();
AssociatedObject.PasswordChanged -= OnPasswordChanged;
}
private void OnPasswordChanged(object sender, RoutedEventArgs e)
{
AssociatedObject.GetBindingExpression(PasswordBox.PasswordProperty).UpdateSource();
}
}
Ussage:
<PasswordBox x:Name="Password" Password="{Binding Password, Mode=TwoWay}" >
<i:Interaction.Behaviors>
<common:UpdateSourceOnPasswordChangedBehavior/>
</i:Interaction.Behaviors>
</PasswordBox>
Ответ 6
UpdateSourceTrigger = Явный не работает для меня, поэтому Im использует собственный класс, полученный из TextBox
public class TextBoxEx : TextBox
{
public TextBoxEx()
{
TextChanged += (sender, args) =>
{
var bindingExpression = GetBindingExpression(TextProperty);
if (bindingExpression != null)
{
bindingExpression.UpdateSource();
}
};
}
}
Ответ 7
Это только одна строка кода!
(sender as TextBox).GetBindingExpression(TextBox.TextProperty).UpdateSource();
Вы можете создать общее событие TextChanged (например, "ImmediateTextBox_TextChanged" ) в коде за вашей страницей и связать его с любым текстовым полем на странице.
Ответ 8
Я принял преторианский ответ и сделал класс расширения, наследующий TextBox
, поэтому вам не нужно путать ваш код вида с этим поведением.
C-Sharp:
public class TextBoxUpdate : TextBox
{
public TextBoxUpdate()
{
TextChanged += OnTextBoxTextChanged;
}
private void OnTextBoxTextChanged(object sender, TextChangedEventArgs e)
{
TextBox senderText = (TextBox)sender;
BindingExpression bindingExp = senderText.GetBindingExpression(TextBox.TextProperty);
bindingExp.UpdateSource();
}
}
VisualBasic
Public Class TextBoxUpdate : Inherits TextBox
Private Sub OnTextBoxTextChanged(sender As Object, e As TextChangedEventArgs) Handles Me.TextChanged
Dim senderText As TextBox = DirectCast(sender, TextBox)
Dim bindingExp As BindingExpression = senderText.GetBindingExpression(TextBox.TextProperty)
bindingExp.UpdateSource()
End Sub
End Class
Затем вызовите это в XAML:
<local:TextBoxUpdate Text="{Binding PersonName, Mode=TwoWay}"/>