WPF tip: executing code after UI has finished updating

willemodendaal
The Curious Coder
Published in
1 min readApr 28, 2016

I faced an interesting challenge, where a data-bound property executed logic, but before the Visual Tree had refreshed, so my control did not work as expected.

The ViewModel was perfectly fine, but the UI just had not caught up yet. So I had to execute the data-binding logic later. Here is how I did it:

private static void BindablePropChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var cc = d as MyCustomControl;
if(cc != null)
{
cc.Dispatcher.BeginInvoke(
DispatcherPriority.ContextIdle, new Action(() =>
{
ChangeSelectedItem(tv, e.NewValue, 0);
}));
}
}

The important part is the DispatcherPriority. Because it was set to ContextIdle, the action only executes when all other threads have finished doing what they needed to do, including updating the UI based on the ViewModel.

Useful!

--

--

willemodendaal
The Curious Coder

Full stack developer and technology geek; Livin’ the dream!