c# - 如何根据对象属性动态更新 DataTemplate?
问题描述
我有一组具有不同呈现选项的对象:它们可以是简单文本、可编辑文本、组合框或事件混合包(如组合框,其中项目通常是文本但带有特定值的图像)。
我设法通过在以下节点内使用来正确ContentTemplateSelector
显示ContentPresenter
所有DataTemplate
内容ListViewItem.ItemTemplate
:
<ContentPresenter
Grid.Row="1"
Grid.Column="1"
Content="{Binding .}"
ContentTemplateSelector="{DynamicResource ResourceKey=RenderTemplateSelector}"/>
(请注意,一切都在DataTemplate
a内ListView.ItemTemplate
)
一切都很好,直到我更改所述属性的值并需要更改模板,例如从图像变为文本。VM 确实正确更新了这些值,但 GUI 中没有任何反应。
环顾四周,有一些方法(使用 a Converter
(绑定到哪个属性??),定义 a Style
(我认为不相关,因为我必须显示不同的控件,而不是更改同一个控件的属性),使用AttachedProperty
(我不'不太了解附加属性是如何工作的,但从我所见,我应该有一个ContentControl
节点,但我没有......)但似乎没有什么我需要的。
所以,回顾一下:我有一个 ListView,它DataTemplate
为每个ListViewItem
包含另一个DataTemplate
需要根据ListViewItem
对象的属性进行更改的定义。我设法用 a 实现了这一点ContentTemplateSelector
,但它是在开始时分配的,然后从未改变过。
解决方案
您可以尝试将 替换为ContentPresenter
具有设置ContentControl
的Style
数据触发器,例如ContentTemplate
:
<ContentControl Content="{Binding}">
<ContentControl.Style>
<Style TargetType="ContentControl">
<Style.Triggers>
<DataTrigger Binding="{Binding YourProperty}" Value="Type1">
<Setter Property="ContentTemplate" Value="{StaticResource template1}" />
</DataTrigger>
<DataTrigger Binding="{Binding YourProperty}" Value="Type2">
<Setter Property="ContentTemplate" Value="{StaticResource template2}" />
</DataTrigger>
<!-- ... -->
</Style.Triggers>
</Style>
</ContentControl.Style>
</ContentControl>
推荐阅读
- regex - 正则表达式匹配特定字符串,但只匹配新行上的第一个字符串
- css - .left-column[] 和 .right-column][] 不对齐
- angular - Databinding with A-Frame
- mongodb - Is better to have multiple collections with thousands of documents or one collection with 100 million documents?
- python - VSCode Python package inspection failure
- visual-studio-code - Visual Studio Code 中的 Jupyter 笔记本不使用活动虚拟环境
- php - 使用 facebook webdriver 清除 textarea
- reactjs - 让用户决定一个页面中有多少项
- python - 使用数据科学库运行 Python 代码时的奇怪问题
- javascript - React - 如何防止来自子组件的点击事件