[英]WPF Designer DataTemplate.DataType cannot be type object
我有一个树视图,我绑定了一些自定义视图模型。 viewmodels 在ObservableCollection
中并继承ViewModelBase
继承INotifyPropertyChanged
。
它编译并运行良好,但在设计器中我收到错误:
“DataTemplate.DataType 不能是类型 object
参数名称:值”
我的 XAML 是:
<TreeView Grid.Row="1" ItemsSource="{Binding ResultsTree}" SelectedItemChanged="TreeView_OnSelectedItemChanged">
<TreeView.Resources>
<HierarchicalDataTemplate DataType="{x:Type local:TreeViewItemViewModel}" ItemsSource="{Binding Path=Children}">
<StackPanel Orientation="Horizontal">
<CheckBox IsChecked="{Binding IsChecked}"/>
<TextBlock Text="{Binding Text}"/>
</StackPanel>
</HierarchicalDataTemplate>
<DataTemplate DataType="{x:Type local:CorrectionAndFreqViewModel}">
<StackPanel Orientation="Horizontal" ToolTip="{Binding AmbientText}">
<Rectangle Width="20" Height="5" Fill="{Binding LineColor, Converter={StaticResource ColorToSolidColorBrushValueConverter}}"></Rectangle>
<CheckBox IsChecked="{Binding IsChecked}"/>
<TextBlock Text="{Binding Text}"/>
</StackPanel>
</DataTemplate>
</TreeView.Resources>
</TreeView>
属性 window 也表示它是 Object,但我不知道为什么:
有任何想法吗?
我能够通过将 ax:Key 添加到 DataTemplate 来解决这个 WPF Designer Bug
<ResourceDictionary>
<DataTemplate x:Key="ThisKeySolvesDesignersNullRef"
DataType="viewmodels:MyViewModel">
<views:MyView/>
</DataTemplate>
</ResourceDictionary>
我一直在寻找几个月,因为它最终出现在不同的项目中,有时会在没有明确原因的情况下出现和消失。 感谢对 SO 的帮助回答
我认为它希望您使用接口类型而不是类类型。
因此,如果您定义一个接口ICorrectionAndFreqViewModel
来公开您将用于数据绑定的所有属性,然后让CorrectionAndFreqViewModel
实现该接口,那么您应该会很好。
就像你说的,代码仍然可以编译和运行,而无需在这里使用接口。 我的猜测是为什么设计者抱怨这个是数据绑定只能在public
属性上使用,所以通过使用接口,可以保证所有属性都是public
。
您应该有一个 xmlns 标记,如local
、 l
或类似的标记。 在数据类型中,您需要使用local:CorrectionAndFreqViewModel
而不是{x:Type CorrectionAndFreqViewModel}
。 如果您没有这些 xmlns 值之一,那么您需要定义它,以便它指向您正在使用的 dll(或者如果您正在查看另一个项目,则使用不同的标记,例如xmlns:msl="clr-namespace:MediaSystems"
)
我有同样的问题。 要修复,请执行以下操作:
Tool
> Option
> XAML
> Uncheck Automaticaly name interactive...
。Visual Studio
,然后问题就会消失。我能够通过确保文件名与类名完全一样来解决这个问题。
在属性中将 'DataType' 设置为您的实际视图模型类型(例如,在您的情况下为 CorrectionAndFreqViewModel),而不是 'object'。
希望这能解决问题。
如果满意,请标记为答案。
理想情况下,它应该自动在属性中选择正确的数据类型,在我的情况下它工作正常。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.