WP7 essendo basato sul Silverlight 3 non supporta nativamente UpdateSourceTrigger = PropertyChanged. Per ovviare a ciò non ci resta che creare una classe ad hoc di supporto:
BindingUtility.
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);
}
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)
{
UpdatePropertyChangedTextBox(s as TextBox);
}
public static void UpdatePropertyChangedTextBox(TextBox textBox)
{
if (textBox == null)
return;
var bindingExpression = textBox.GetBindingExpression(TextBox.TextProperty);
if (bindingExpression != null)
{
bindingExpression.UpdateSource();
}
}
}
|
L'utilizzo della classe è veramente semplice:
xmlns:utility="clr-namespace:XXX.Utility"
<TextBox Text="{Binding TuaProprieta,Mode=TwoWay}" utility:BindingUtility.UpdateSourceOnChange="True"/>
|
Nessun commento:
Posta un commento