WPF和MVVM相当新,我正在尝试将ContentTemplate(或ItemTemplate,都没有起作用)绑定到C#WPF程序中的DataTemplate属性。我这样做是因为我有一个配置文件,该文件为每个“条目”定义了不同的“条目显示类型”,以试图不必制作无数个视图/视图模型(现在,只有一个通用条目viewmodel可以跟踪标签,数据和显示类型),我宁愿保持这种方式以避免类结构的不必要膨胀。有什么办法可以使这项工作吗?
这是我尝试过的事情之一的示例:
XAML:
<ItemsControl IsTabStop="False" ItemsSource="{Binding Path=FNEntries}"Margin="12,46,12,12">
<ItemsControl.ItemTemplate>
<DataTemplate>
<ContentControl ContentTemplate="{Binding Path=TypeView}" />
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
Run Code Online (Sandbox Code Playgroud)
CS(在具有(DataTemplate)TypeView和(string)PropertyName的入口视图模型类构造函数中):
NodeTypeView = (DataTemplate)Application.Current.FindResource("TypeTest");
Run Code Online (Sandbox Code Playgroud)
资源XAML:
<DataTemplate x:Key="TypeTest">
<TextBlock Margin="2,6">
<TextBlock Text="{Binding Path=PropertyName}" />
</TextBlock>
Run Code Online (Sandbox Code Playgroud)
当我这样做时,什么都没有显示。但是,如果我直接将资源数据模板的内容替换为内容控件,则一切都会很好地显示出来(除了它不是我所希望的数据驱动)。任何帮助/建议将不胜感激。谢谢!