C# 如何将URI设置为来自另一个程序集的ResourceDictionary中的对象? 什么有效

C# 如何将URI设置为来自另一个程序集的ResourceDictionary中的对象? 什么有效,c#,wpf,xaml,resources,C#,Wpf,Xaml,Resources,我正在使用一个名为“WPF动画GIF”的插件,它允许我将动画GIF设置为图像源。我的问题是,我正在使用另一个项目的图像。这些图像是ResourceDictionary中的键,如下所示: <ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xam

我正在使用一个名为“WPF动画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>
ImageBehavior.SetAnimatedSource(SyncImage, TryFindResource("ImgSyncSucceeded"));
我不喜欢这样设置,现在也不行,因为路径设置为“Images”,它在同一个项目中

ImageBehavior.SetAnimatedSource(SyncImage, TryFindResource("ImgSyncSucceeded"));

那么,如何将其设置为使用XAML代码中的StaticResources呢?

资源字典使用查找树,因此首先它将查找控件资源,然后它将查找可视树,直到找到资源为止,只要可视树中的条目高于默认值,那么您的值将被覆盖

ImageBehavior.SetAnimatedSource(SyncImage, TryFindResource("ImgSyncSucceeded"));
但是,当您使用代码隐藏绕过静态资源时,如果您使用
TryFindResource(ResourceKey)
将保持资源字典查找的完整性,则会中断连接

ImageBehavior.SetAnimatedSource(SyncImage, TryFindResource("ImgSyncSucceeded"));
所以

ImageBehavior.SetAnimatedSource(SyncImage, TryFindResource("ImgSyncSucceeded"));
静态资源也应该是静态的,即不改变,所以使用动态资源有助于

使用值转换器,您可以做到这一点(请注意,这是未经测试的代码,仅作为一般原理的示例提供)

ImageBehavior.SetAnimatedSource(SyncImage, TryFindResource("ImgSyncSucceeded"));
在XAML中使用以下命令

ImageBehavior.SetAnimatedSource(SyncImage, TryFindResource("ImgSyncSucceeded"));
<Window.Resources>
    <l:SyncConverter x:Key="converter" Synced="{StaticResource ImgSyncSucceeded}" Desynced="{StaticResource ImgSyncFailed}" Syncing="{StaticResource ImgSyncing}"/>
</Window.Resources>

<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="{Binding syncStatus, Converter={Static converter}}" HorizontalAlignment="Center" VerticalAlignment="Center" Width="100" Height="100"/>
</Button>


您可能需要将TryFindResource的返回值强制转换为ImageSource.Awesome。这使我的开关盒短得多。我讨厌那些乌里的!谢谢你!对于WPF,这确实不应该通过代码隐藏来完成,您应该绑定到syncStatus,然后使用多重绑定或值转换器来选择正确的图像DataTemplateSelector也可以工作