【发布时间】:2021-01-05 20:22:29
【问题描述】:
我正在尝试使用自定义数据模板创建一个组合框,但会有多个组合框使用相同的模板,因此我想将其设为资源。它不起作用,所以我创建了一个简单的测试项目来测试它,果然我遇到了同样的问题。这是 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 类只是选项的 DataItems 列表和要绑定到的选定选项。
当我启动这个应用程序时,我得到了这个异常:
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.
该资源清楚地在那里并且拼写正确,但它显示它找不到它。为什么不???
我还尝试了以下方法:
- 取出密钥,使其成为该类型的默认模板。这不会产生错误,但也不会应用模板,因此基本上会被忽略。
- 直接将模板放入
ComboBox。我已经确认这可以按预期工作,但正如我所说,我的应用中有很多ComboBoxes,所以不必每次都创建模板会很棒...
有人知道为什么这不起作用吗?肯定有一种方法可以从资源中设置项目模板……对吧?
【问题讨论】:
-
如果你不偷懒写
{x:Type}:<DataTemplate DataType="{x:Type local:DataItem}" x:Key="DtTest" > -
谢谢。是不是懒惰只是不知道我在那里需要它......无论如何,如果我输入 x:Type 符号,你是对的,它似乎确实可以接受它。不知道为什么没有它它就无法识别,但我想这就是它的工作方式。感谢您的教育:)。
标签: c# wpf combobox datatemplate