我正在使用一个名为“ WPF Animated GIF”的插件,该插件使我可以将gif动画设置为图像的图像源。我的问题是我正在使用另一个项目中的图像。这些图像是ResourceDictionary中的键,如下所示:
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
...
<ImageSource x:Key="ImgSyncFailed">Images/Sync Failed.png</ImageSource>
<ImageSource x:Key="ImgSyncSucceeded">Images/Sync Succeeded.png</ImageSource>
<ImageSource x:Key="ImgSyncing">Images/Syncing-Small.gif</ImageSource>
</ResourceDictionary>
资源字典通过引用和XAML添加到另一个项目中:
<Window.Resources>
<ResourceDictionary Source="pack://application:,,,/ResourcesDictionary;component/Dictionary.xaml"/>
</Window.Resources>
当您想通过XAML添加图像时,这工作得很好:
<Button x:Name="SyncButton" Focusable="False" Background="{x:Null}" BorderBrush="{x:Null}" Foreground="{x:Null}" Height="100" Width="100" Click="SyncButton_OnClick">
<Image x:Name="SyncImage" gif:ImageBehavior.AnimatedSource="{StaticResource ImgSyncSucceeded}" HorizontalAlignment="Center" VerticalAlignment="Center" Width="100" Height="100"/>
</Button>
当我切换按钮的图像时,我是通过代码来完成的:
private void ChangeSyncImage()
{
switch (syncStatus)
{
case SyncStatus.Synced:
...
case SyncStatus.Desynced:
...
case SyncStatus.Syncing:
var img3 = new BitmapImage();
img3.BeginInit();
img3.UriSource = new Uri("pack://application:,,,/SmartFridgeApplication;component/Images/Syncing-Small.gif");
img3.EndInit();
ImageBehavior.SetAnimatedSource(SyncImage, img3);
break;
}
}
我不喜欢这样设置,并且现在不起作用,因为该路径设置为同一项目中的“图像”。
那么,如何将其设置为使用XAML代码中的StaticResources?
资源字典使用查找树,因此首先将查找控件资源,然后将查找可视树,直到找到资源为止,只要您在可视树中的输入高于默认值,便会查找值将覆盖
但是,当您使用后面的代码绕过静态资源时,如果您断开连接,则将断开连接TryFindResource(ResourceKey)
,将使资源字典查找保持完整
所以
ImageBehavior.SetAnimatedSource(SyncImage, TryFindResource("ImgSyncSucceeded"));
静态资源也应该是静态的,即不要更改,因此使用动态资源可以帮助https://msdn.microsoft.com/zh-cn/library/ms748942%28v=vs.110%29.aspx
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句