DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones AWS Cloud
by AWS Developer Relations
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones
AWS Cloud
by AWS Developer Relations

Throttling Immediate TextBox Binding Behavior for Windows Phone

Slobodan Pavkov user avatar by
Slobodan Pavkov
·
Jun. 17, 12 · Interview
Like (0)
Save
Tweet
Share
4.79K Views

Join the DZone community and get the full member experience.

Join For Free

the learning curve of a windows phone developer

while developing offline web browser for windows phone i had to build a small mvvm framework in order to keep the logic out of the views.

one of the first things i found missing was a way to force immediate propagation of text entered in textbox control to the databound property of my viewmodel.

by default, textbox binding is triggered only when control loses focus, and this is kind of lame.

code reuse is not a myth!

this is really old problem. it existed in desktop silverlight from the beginning. and it made its way to the windows phone platform.

fortunately i remembered that back in the days while experimenting with silverlight mvvm framework i already solved this problem by creating a custom silverlight textbox control so i decided to just reuse that code and create a behavior that will force binding update to fire on each keystroke in textbox.

that’s the beauty of developing a windows phone app – you can reuse most of the silverlight code you built over the years :)

but then i noticed another problem. because now each keystroke was propagating changes to my viewmodel, if user would type fast and i do for example some web service call on each property change – then i can have too many requests to the web service (one for each keystroke) but in fact i want to do a call only when user stopped typing for a while.

fortunately, solution is very simple – we will use reactive extensions (rx) since its perfect fit and its already built-in into windows phone.

we just need to reference microsoft.phone.reactive.dll from gac (no additional download needed) and we are half-way there.

ok, but show us some code!

yes lets see how the code for the throttledimmediatebindingbehavior looks like:

using system;
using system.windows;
using system.windows.controls;
using system.windows.data;
using system.windows.interactivity;
using microsoft.phone.reactive;

namespace roboblob.mvvm.behaviors
{
    public class throttledimmediatebindingbehavior : behavior
    {
        private bindingexpression _expression;

        public bool throttle { get; set; }

        private double _throttledelayinseconds = 0.5;
        private idisposable _currentobservable;

        public double throttledelayinseconds
        {
            get { return _throttledelayinseconds; }
            set { _throttledelayinseconds = value; }
        }

        protected override void onattached()
        {
            base.onattached();

            if (throttle)
            {
                this._expression = this.associatedobject.getbindingexpression(textbox.textproperty);
                var keys = observable.fromevent(associatedobject, "textchanged").throttle(timespan.fromseconds(throttledelayinseconds));
                _currentobservable = keys.observeon(deployment.current.dispatcher).subscribe(evt => ontextchanged(evt.sender, evt.eventargs));
            }
            else
            {
                this._expression = this.associatedobject.getbindingexpression(textbox.textproperty);
                this.associatedobject.textchanged += this.ontextchanged;
            }
        }

        protected override void ondetaching()
        {
            base.ondetaching();

            if (throttle)
            {
                if (_currentobservable != null)
                {
                    _currentobservable.dispose();
                    this._expression = null;
                }
            }
            else
            {
                this.associatedobject.textchanged -= this.ontextchanged;
                this._expression = null;
            }
        }

        private void ontextchanged(object sender, eventargs args)
        {
            if (_expression != null)
            {
                this._expression.updatesource();
            }
        }
    }
}

simple is beautiful

our binding class has bool property throttle where we can enable/disable throttling and also a throttledelayinseconds where we specify after how many seconds later after user stops typing our property is updated.

in the onattached – we just hook to the textchanged and each time user types something we update the binding source.

but if throttle is set to true, we hook to the textchanged event over reactive extensions and we setup throttling so that binding do not trigger if changes are too fast.

in this only after changes stop firing for the time defined in throttledelayinseconds, only then binding update is triggered.

off course we do a little cleanup in the ondetaching as all good coders :)

what about the xaml???

yes in xaml we can use it like this:

<textbox text="{binding searchcriteriatext, mode=twoway}">
                <i:interaction.behaviors>
                    <roboblobbehaviors:throttledimmediatebindingbehavior throttle="true" throttledelayinseconds="1" />
                </i:interaction.behaviors>
            </textbox>

for those who are lazy to type i’m attaching a zipped source code of simple windows phone mango project that is demonstrating the usage of the behavior.

btw does somebody even remember how it was to type source code from printed computer magazines int your 8bit computer?

probably not :d

well at least i hope that someone will find this useful.

until next time, happy coding!

Windows Phone Binding (linguistics)

Published at DZone with permission of Slobodan Pavkov, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • Strategies for Kubernetes Cluster Administrators: Understanding Pod Scheduling
  • DevOps for Developers — Introduction and Version Control
  • A Deep Dive Into AIOps and MLOps
  • Multi-Tenant Architecture for a SaaS Application on AWS

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: