Friday, October 30, 2009

WPF binding to a fast changing data source

I was using wpf data binding to display data in a real time monitoring application and found the rate at which the data source was changing resulted in a difficult to read control.

Josh Smith has a good article on ways to reduce the frequency of binding updates and the option of calling UpdateTarget on the controls binding expression was the most appropriate solution for my application. The WPF user controls that I was applying this to had a large number of controls and so I needed a way of finding the binding expressions for all the controls.

Philipp Sumi has a function (FindChildren) to find all child control of a specified type which I used to locate and subsequently update all relevant binding expressions for the control type I was using (TextBlock)

public partial class BindingSample : UserControl

        List<BindingExpression> _bindingExpressions = new List<BindingExpression>();

        public BindingSample()

            foreach (var tb in this.FindChildren<TextBlock>() )
                BindingExpression be = tb.GetBindingExpression(TextBlock.TextProperty);
                if (be != null)

        // Force binding update 
        // NB: Not using OneWay binding because updates are too frequent
        //     An alternative would be to use the converter UpdateThresholdConverter
        //     but this would not necessarily result in the last value being displayed when updates stop.
        public void UpdateTarget()
            _bindingExpressions.ForEach(e => e.UpdateTarget());


            <StackPanel Style="{StaticResource DisplayLabelValue}">
                <Label Style="{StaticResource DisplayTitle}">Speed</Label>
                <TextBlock Style="{StaticResource DisplayValue}" Text="{Binding Path=Speed, Mode=OneTime, StringFormat=F1}"/>

Source code for FindChildren (by Philipp Sumi)