Wp7 Application Bar, update binding helper

As you may have read I’ve been having ‘fun’ with the Application Bar. Following the really useful post by Laurent Bugnion, I’ve written the following helper that allows you to quickly manage your editable bindable controls. It’s not as simple as I hoped, I’d prefer to be able to get the helper to search for bindable properties but I’ve yet to find a nice way to achieve this – as always I welcome suggestions. Anyway hope this helps;

using System;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Media;
using System.Collections.Generic;
using System.Windows.Data;

namespace pauliom.Helpers
{
    public class BindingHelper
    {
        private BindingHelper(){}

        private IEnumerable<BindingExpression> bindables;
        public BindingHelper(DependencyObject parent, Type type, DependencyProperty property)
        {
            bindables = GetChildsRecursive(parent).OfType<FrameworkElement>().
                Where(c => c.GetType() == type && c.GetBindingExpression(property) != null).
                Select(c => c.GetBindingExpression(property));
        }

        public void UpdateAllBindings()
        {
            if (bindables != null)
            {
                foreach (BindingExpression binding in bindables)
                {
                    binding.UpdateSource();
                }
            }
        }

        // code from 'tucod'
        IEnumerable<DependencyObject> GetChildsRecursive(DependencyObject root)
        {
            List<DependencyObject> elts = new List<DependencyObject>();
            elts.Add(root);
            for (int i = 0; i < VisualTreeHelper.GetChildrenCount(root); i++)
                elts.AddRange(GetChildsRecursive(VisualTreeHelper.GetChild(root, i)));

            return elts;
        }
    }
}

So to use the code you create helper per type of control and property you want to keep updated;

private BindingHelper bindingForGridTextBoxes;
void Page_Loaded(object sender, RoutedEventArgs e)
{
      this.bindingForGridTextBoxes = 
                new BindingHelper(LayoutRoot, typeof(TextBox), TextBox.TextProperty);
      this.DataContext = viewModel;
}

then whereever you need to ensure the bindings are up-to-date, e.g. when one of the cheeky non-framework Application Bar buttons are clicked;

this.bindingForGridTextBoxes.UpdateAllBindings();
Advertisements
This entry was posted in Uncategorized, wp7, wp7dev. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s