Redundant converter calls when using Triggers to determine value
I noticed that my XAML markup is wasting resources by doing conversions which it is not supposed to do开发者_运维百科. e.g. i have the following Style which acts as a switch:
<Style TargetType="{x:Type Image}">
<Style.Triggers>
<DataTrigger Binding="{Binding IsDownloaded}" Value="True">
<Setter Property="Source"
Value="{Binding Data, Converter={StaticResource ByteArrayToBitmapImageConv}}"/>
</DataTrigger>
<DataTrigger Binding="{Binding IsDownloaded}" Value="False">
<Setter Property="Source"
Value="{Binding Url, Converter={StaticResource UrlToBitmapImageConv}}"/>
</DataTrigger>
</Style.Triggers>
</Style>
Obviously this should either download an image if it has not been cached or turn the raw data into a BitmapImage. The problem is that as soon as both cases have taken place at least once both converters are called when the DataContext changes, irrespectively of the value that IsDownloaded
has. So it will either display the converted image but still download it independendly in the background or it will download the image and try to convert null
(the data) to a BitmapImage.
Setting the binding mode to OneTime
did not help sadly.
I am looking for a clean way to avoid this as it even occurs multiple times in my application. e.g. here:
<Style TargetType="ContentControl">
<Setter Property="Content" Value="{StaticResource ContentNothingSelected}"/>
<Style.Triggers>
<DataTrigger Binding="{Binding Source={x:Static local:App.Settings}, Path=DisplayMode_Current}"
Value="Description">
<Setter Property="Content" Value="{StaticResource DescriptionViewer}"/>
</DataTrigger>
<DataTrigger Binding="{Binding Source={x:Static local:App.Settings}, Path=DisplayMode_Current}"
Value="WebPage">
<Setter Property="Content" Value="{StaticResource WebPageViewer}"/>
</DataTrigger>
<DataTrigger Binding="{Binding Source={x:Static local:App.Settings}, Path=DisplayMode_Current}"
Value="Media">
<Setter Property="Content" Value="{StaticResource MediaViewer}"/>
</DataTrigger>
</Style.Triggers>
</Style>
Even if the display mode is set to Media
or Description
the application will navigate to the corresponding site in the background, wasting resources and throwing occasional out of place Javascript-error notifications.
I previously did most of this in code but i remodelled it to be more declarative and i would like to keep it that way, any help would be appreciated.
You could reconsider using Triggers and instead use a custom control and the Visual State Manager. Put the logic of downloading and caching and converting images in the custom control and simply set the appropriate states. It's hard to give an example without more xaml I'm afriad.
精彩评论