Task.Delay to help debug binding timing issue

1 1 1 1 1 1 1 1 1 1 Rating 0.00 (0 Votes)

Task.Delay to help debug binding timing issue


While working on my recent windows phone 8.1 XAML app, I came across a situation which needed different AppBarButton to be displayed for different states. I used a converter to bind to the visibility attribute of the AppBarButtons as in the sample xaml snippet

<AppBarButton x:Name="appAddChart" Visibility="{Binding CommandGroup, ConverterParameter=1, Converter={StaticResource cmdGroupConverter}}" Label="add" Icon="Add" Click="appAddChart_Click"/>
            <AppBarButton x:Name="appMultiSelect" Visibility="{Binding CommandGroup, ConverterParameter=1, Converter={StaticResource cmdGroupConverter}}" Label="select"  Icon="List" Click="appMultiSelect_Click"/>
            <AppBarButton x:Name="appEdit" Label="edit" Visibility="{Binding CommandGroup, ConverterParameter=2, Converter={StaticResource cmdGroupConverter}}" Icon="Edit" Click="appEditButton_Click"/>
            <AppBarButton x:Name="appMoveTo" Visibility="{Binding CommandGroup, ConverterParameter=2, Converter={StaticResource cmdGroupConverter}}" Label="move" Icon="MoveToFolder" Click="appMoveTo_Click"/>

 
The code and logic all seemed perfect still the binding was not working. There was no binding error in the logs. After reading through different forums I realized this could be a timing issue. The binding is not complete before the change of data in ViewModel is performed in the C# code (say in OnNavigatedTo event). I found that Task.Delay could be an awesome tool to confirm such theory. Just add a line as below:

await Task.Delay(TimeSpan.FromSeconds(.7));

 
Below is the complete snippet:

             await Task.Delay(TimeSpan.FromSeconds(.1));
             AppBarStatusViewModel appBarVM = new AppBarStatusViewModel();
             BottomAppBar.DataContext = appBarVM;
             appBarVM.CommandGroup = 1;

The 0.1 sec of delay added gives enough time to complete the binding before the ViewModel state is changed for it to trigger the necessary condition in the UI.

While Task.Delay should not be used as a solution to all timing issues, it can definitely be used to debug such issues.




Joomla SEO by MijoSEF