找不到 WPF ComboBox 项目模板

问题描述

我正在尝试使用自定义数据模板创建一个组合框,但会有多个组合框使用相同的模板,因此我想将其作为资源。它不起作用,所以我创建了一个简单的测试项目来测试它,果然我遇到了同样的问题。这是 XAML 代码

<Window x:Class="TemplateTest.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:TemplateTest"
        mc:Ignorable="d"
        d:DataContext="{d:DesignInstance Type={x:Type local:viewmodel}}"
        Title="MainWindow" Height="450" Width="800">
    <Window.Resources>
        <ResourceDictionary>
            <DataTemplate DataType="local:DataItem" x:Key="DtTest">
                <TextBlock Text="{Binding Name}" />
            </DataTemplate>
        </ResourceDictionary>
    </Window.Resources>
    <Grid>
        <StackPanel>
            <ComboBox ItemsSource="{Binding NameOptions}" 
                      SelectedItem="{Binding Selectedname}"
                      ItemTemplate="{StaticResource DtTest}"/>
        </StackPanel>
    </Grid>
</Window>

如果有人真的想看到它,我也可以发布其他代码,但 DataItem 类只是一个具有单个“名称”字符串属性的类。 viewmodel 类只是选项的 DataItem 列表和要绑定到的选定选项。

当我启动此应用程序时,出现此异常:

System.Windows.Markup.XamlParseException
  HResult=0x80131501
  Message='Provide value on 'System.Windows.StaticResourceExtension' threw an exception.' Line number '19' and line position '14'.
  Source=PresentationFramework
  StackTrace:
   at System.Windows.Markup.WpfXamlLoader.Load(XamlReader xamlReader,IXamlObjectWriterFactory writerFactory,Boolean skipJournaledProperties,Object rootObject,XamlObjectWriterSettings settings,Uri baseUri)
   at System.Windows.Markup.WpfXamlLoader.LoadBaml(XamlReader xamlReader,XamlAccessLevel accessLevel,Uri baseUri)
   at System.Windows.Markup.XamlReader.LoadBaml(Stream stream,ParserContext parserContext,Object parent,Boolean closeStream)
   at System.Windows.Application.LoadComponent(Object component,Uri resourceLocator)
   at TemplateTest.MainWindow.InitializeComponent() in C:\Users\sfaus\source\repos\TemplateTest\TemplateTest\MainWindow.xaml:line 1

  This exception was originally thrown at this call stack:
    [External Code]

Inner Exception 1:
Exception: Cannot find resource named 'DtTest'. Resource names are case sensitive.

资源清楚地存在且拼写正确,但显示无法找到。为什么不???

我还尝试了以下方法

  • 取出密钥,使其成为该类型的认模板。这不会产生错误,但也不会应用模板,因此它基本上会被忽略。
  • 直接将模板放入 ComboBox。我已经确认这按预期工作,但正如我所说,我的应用中有很多这样的ComboBox,因此不必每次都创建模板会很棒...立>

有人知道为什么这不起作用吗?肯定有一种方法可以从资源中设置项目模板...对吗?

解决方法

好的,经过进一步的搜索和调查,我想我发现了问题。似乎您无法指定 Key 和数据类型,否则会吓坏了。错误消息非常具有误导性,但这似乎是问题所在。如果我取出数据类型名称,它就会开始工作。为了保持我的智能感知,我在模板的根对象上设置了设计时数据上下文,所以这里是更新的模板:

<DataTemplate x:Key="DtTest">
    <TextBlock d:DataContext="{d:DesignInstance Type={x:Type local:DataItem}}" Text="{Binding Name}" />
</DataTemplate>

那仍然不能解释为什么只有数据类型不起作用,但至少这让它对我有用。如果有人有任何关于他们为什么在那里的进一步信息,我很乐意接受比我更详细的答案。