首页 > 解决方案 > 未找到 WPF 组合框项目模板

问题描述

我正在尝试使用自定义数据模板创建一个组合框,但会有几个组合框使用相同的模板,所以我想将其作为资源。它不起作用,所以我创建了一个简单的测试项目来测试它,果然我遇到了同样的问题。这是 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, Boolean skipJournaledProperties, Object rootObject, 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.

该资源显然在那里并且拼写正确,但它显示它找不到它。为什么不???

我还尝试了以下方法:

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

标签: c#wpfcomboboxdatatemplate

解决方案


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

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

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


推荐阅读