资源无法解析

3

我收到了一个错误信息:"找不到资源ComponentTypeToStringConverter",请问我做错了什么?

我有一个下拉框:

<ComboBox SelectedItem="{Binding PcComponent.ComponentTypeName}" Grid.Column="1" Grid.Row="2" Grid.ColumnSpan="2">
      <ComboBox.ItemTemplate>
           <DataTemplate>
                 <TextBlock Text="{Binding Converter={StaticResource ComponentTypeToStringConverter}}"/> <!-- HERE I got a error The resource "ComponentTypeToStringConverter could not be resolved -->
           </DataTemplate>
      </ComboBox.ItemTemplate>
</ComboBox>

资源:

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                    xmlns:c="clr-namespace:PcConfigurator.Converters">
    <c:ComponentTypeToStringConverter x:Key="ComponentTypeToStringConverter"/>
</ResourceDictionary>

转换器(命名空间PcConfigurator.Converters):

public class ComponentTypeToStringConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            if (!(value is ComponentType)) { return null; }

            ComponentType type = (ComponentType)value;

            switch (type)
            {
               //Do something
            }

            throw new InvalidOperationException("Enum value is unknown");
        }

        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            throw new NotSupportedException();
        }
}

你是否在你的app.xaml中包含了ResourceDictionary,并且在没有代码后端编译器错误的情况下构建它?我只是假设命名空间在同一个程序集中! - Silvermind
1个回答

17
在设计时,您的资源尚未编译,并且当前具有ComboBoxXAML文件无法看到ResourceDictionary
假设您的资源在App.xaml中定义,那么在运行时运行时,应该不会遇到任何问题,因为它将能够找到key
如果您想在设计时消除错误,可以在ComboBox所在的XAML文件中添加ResourceDictionary,以便它能够找到它。
假设这是一个Window,并且您有一个未在App.xaml中定义而是作为单独文件的ResourceDictionary
<Window.Resources>
 <ResourceDictionary Source=""/>
</Window.Resources>

2
在不同的论坛和格式中,这个问题有10多个答案,但只有这一个对我真正起作用。当解释时显而易见。干杯! - Oyiwai

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接