gpt4 book ai didi

c# - 如何将 URI 设置为来自另一个程序集的 ResourceDictionary 中的对象?

转载 作者:太空宇宙 更新时间:2023-11-03 23:40:54 24 4
gpt4 key购买 nike

什么有效

我正在使用一个名为“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?

最佳答案

资源字典使用查找树,所以首先它会查找控件资源,然后它会查找可视化树直到找到资源,所以只要您在可视化树中的条目高于默认值value 那么你的值将覆盖

然而,当您使用后面的代码绕过静态资源时,如果您使用 TryFindResource(ResourceKey),您将断开连接,您将保持资源字典查找的完整性

所以

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

静态资源也应该是静态的,即不会改变,因此使用动态资源可能有助于 https://msdn.microsoft.com/en-us/library/ms748942%28v=vs.110%29.aspx

关于c# - 如何将 URI 设置为来自另一个程序集的 ResourceDictionary 中的对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29074901/

24 4 0
文章推荐: c - Vigenere cipher in C的几个问题
文章推荐: c# - 使用 Linq to XML 在节点之前插入 XComment
文章推荐: android - AOSP 4.3 : Emulator not starting after adding a HAL module
文章推荐: javascript - 制作带有链接的可点击
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com