Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I prevent flickering when binding a boolean to the visibility of a control

I have a boolean property in my ViewModel, named lets say IsNotSupported that is used to show some warning information if a sensor is not supported. Therefore I use a BooleanToVisibilityConverter, that is added in the ressources:

<phone:PhoneApplicationPage.Resources>
    <local:BooleanToVisibilityConverter x:Key="BooleanToVisibilityConverter" />
</phone:PhoneApplicationPage.Resources>

and bind it to the stackpanel containing the warning:

<StackPanel x:Name="NotSupportedWarning" Visibility="{Binding IsNotSupported,
                    Converter={StaticResource BooleanToVisibilityConverter}}">

That works all quite well, but when loading the page, and the sensor is supported, the warning appears for just a fraction of a second and disappears afterwards. I know that this flickering is caused by the binding not having happened yet and therefore defaulting to visible.

That flicker it is annoying as hell... It should rather default to collapsed and be made visible only after it is clear that the warning should be shown. Also, this would avoid a second layouting pass after the binding and could therefore have positive performance impacts.


I had this problem over and over, and found nothing about it in the internet until I found this SO question, that is closely related, but is not found if searched for windows phone instead of silverlight. Both the problem and the solution might seem simple, but I really bugged me quite a long time, so I thought it might be a good idea to write a Q&A-style question about it to help others that are facing the same issue.

like image 517
Philip Daubmeier Avatar asked Jun 27 '12 15:06

Philip Daubmeier


2 Answers

The solution is simple after you have seen it. You can control the default value of the binding (if the binding didnt happen yet) with FallbackValue. Your stackpanel XAML would look like:

<StackPanel x:Name="NotSupportedWarning" Visibility="{Binding IsNotSupported,
                    FallbackValue=Collapsed, 
                    Converter={StaticResource BooleanToVisibilityConverter}}">

This way you get rid of the flicker and it does not have to be relayouted after the binding, if the warning stays hidden.

like image 52
Philip Daubmeier Avatar answered Nov 18 '22 10:11

Philip Daubmeier


you can bind directly to a Visibility type of property instead of boolean and keep that property to collapsed by default plus you can implement INotifyPropertyChanged

like image 41
CognitiveDesire Avatar answered Nov 18 '22 10:11

CognitiveDesire