资源无法解决

Not*_*tur 3 c# wpf xaml

我收到错误"资源"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>
Run Code Online (Sandbox Code Playgroud)

资源:

<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>
Run Code Online (Sandbox Code Playgroud)

Converter(名称空间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();
        }
}
Run Code Online (Sandbox Code Playgroud)

123*_*9 0 10

设计时.您的资源尚未编译,并且XAML您拥有的当前文件ComboBox无法查看ResourceDictionary.

假设您的资源已定义,App.xaml那么当您在运行时运行它时它应该没有问题,因为它可以找到它key.

如果你想摆脱设计时的错误,那么你可以做的就是你生活中的XAML文件ComboBox,你可以添加它ResourceDictioanry以便它能够找到它.

假设这是一个Window并且你ResourceDictionary没有在那里定义App.xaml但是作为一个单独的文件

<Window.Resources>
 <ResourceDictionary Source=""/>
</Window.Resources>
Run Code Online (Sandbox Code Playgroud)

  • 在不同论坛和格式中出现的这个问题的 10 多个答案中,这是唯一一个真正对我有用的答案。解释起来也很明显。干杯! (2认同)