Here is a quick access answer to the Microsoft solution proposed by Derek. Instead of loading and sifting all the Prism items, simply copy this class into your project, and then follow these steps to activate it:
UpdateBindingOnPropertyChangedBehviour.cs
using System; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Interactivity; namespace MyCompany.MyProduct { /// <summary> /// Custom behavior that updates the source of a binding on a text box as the text changes. /// </summary> public class UpdateTextBindingOnPropertyChanged : Behavior<TextBox> { /// <summary> /// Binding expression this behavior is attached to. /// </summary> private BindingExpression _expression; /// <summary> /// Called after the behavior is attached to an AssociatedObject. /// </summary> /// <remarks> /// Override this to hook up functionality to the AssociatedObject. /// </remarks> protected override void OnAttached() { base.OnAttached(); // Hook events to change behavior _expression = AssociatedObject.GetBindingExpression(TextBox.TextProperty); AssociatedObject.TextChanged += OnTextChanged; } /// <summary> /// Called when the behavior is being detached from its AssociatedObject, but before it has actually occurred. /// </summary> /// <remarks> /// Override this to unhook functionality from the AssociatedObject. /// </remarks> protected override void OnDetaching() { base.OnDetaching(); // Un-hook events AssociatedObject.TextChanged -= OnTextChanged; _expression = null; } /// <summary> /// Updates the source property when the text is changed. /// </summary> private void OnTextChanged(object sender, EventArgs args) { _expression.UpdateSource(); } } }
This is basically a cleaned-up version of Microsoft Prism 4.1 code (see the Silverlight \ Prism.Interactivity project if you want to see the rest).
Now how to use it:
- Add a link to the System.Windows.Interactivity assembly to your Windows Phone project.
- On each page where you want to use the behavior, add a XAML link to the assembly: XMLNS: i = "CLR names: System.Windows.Interactivity; assembly = System.Windows.Interactivity"
Inside the XAML of each TextBox that you want to apply bahvior to (which already has a TwoWay binding to your original property), add the following:
<i: Interaction.Behaviors>
<my: UpdateTextBindingOnPropertyChanged / ">
</ I: Interaction.Behaviors>
Note: the prefix "my:" may differ in your code. This is just a namespace reference in which you added a behavior class.
Tony Wall 02 Oct '12 at 18:54 2012-10-02 18:54
source share