【问题标题】:How can I access a resource from a ValueConverter?如何从 ValueConverter 访问资源?
【发布时间】:2013-04-01 21:08:15
【问题描述】:

我在自定义 DLL 程序集中有一个 UserControl,我在其中定义了两个静态 BitmapImage 资源,它们代表我们的 ItemsControl 中的数据状态。我想根据某些条件使用转换器将 Image 的 Source 属性设置为 BitmapImage 资源之一。但是,我不确定如何从 Convert 方法内部访问资源,因为我没有使用转换器的控件实例。

我尝试将资源加载到转换器的静态构造函数中的静态变量中,该构造函数也在同一个 DLL 中,但我没有成功。

这失败了……

public class MyConverter : IValueConverter
{
    static BitmapImage myFirstResource;
    static MyConverter()
    {
        // This can't seem to find the resource...
        myFirstResource = (BitmapImage)Application.Current.FindResource("MyResourceKey");
    }
}

...但是在 XAML 中,这成功了,所以我知道资源密钥是有效的。

<Image Source="{StaticResource MyResourceKey}" />

我不知道这是否有任何区别,但这是在 DLL 中,而不是在 EXE 中。不过,我认为所有资源都归结为应用程序,具体取决于您执行的位置。

【问题讨论】:

  • 你不是说myFirstResource = (BitmapImage)Application.Current.FindResource("MyResourceKey");吗?
  • 对不起。粘贴错误。固定。
  • 然后删除对任何人都没用的问题。
  • 我为什么要这样做?这个问题仍然有效。我的代码示例在此处重新格式化时出现粘贴错误。很抱歉,但我不同意你的说法。

标签: wpf resources ivalueconverter


【解决方案1】:

在这里找到完美的解决方案Accessing a resource via codebehind in WPF (比使用Application.Current 更好)

@itsho

您可以简单地将x:Class 添加到它:

<ResourceDictionary x:Class="Namespace.NewClassName"
                    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" >
    <ds:MyCollection x:Key="myKey" x:Name="myName" />
</ResourceDictionary>

然后在后面的代码中使用:

var res = new Namespace.NewClassName();
var col = res["myKey"];

然后应该应用一些修复:

@Stephen Ross

但为了能够使用它的密钥查找资源,我必须在尝试访问 key 之前调用 res.InitializeComponent(),否则该对象将不显示任何密钥,并且对 res["myKey"] 的调用将返回 null

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-01-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多