如何根据对象 属性 动态更新 DataTemplate?
How to update a DataTemplate dynamically based on a object property?
我有一组具有不同呈现选项的对象:它们可以是简单文本、可编辑文本、组合框,或者是混合包(例如组合框,其中项目通常是文本,但带有特定值的图像)。
我设法通过在 ListViewItem.ItemTemplate
的 DataTemplate
内的 ContentPresenter
节点内使用 ContentTemplateSelector
来正确显示所有内容:
<ContentPresenter
Grid.Row="1"
Grid.Column="1"
Content="{Binding .}"
ContentTemplateSelector="{DynamicResource ResourceKey=RenderTemplateSelector}"/>
(请注意,所有内容都在 ListView.ItemTemplate
的 DataTemplate
内)
一切都很好,直到我更改上述 属性 的值并需要更改模板,例如从图像变为文本。
VM 确实正确更新了值,但 GUI 中没有任何反应。
环顾四周,有一些方法(使用 Converter
(绑定到 属性??),定义 Style
(我认为不相关,因为我必须显示不同的控件,而不是更改同一控件的属性),使用 AttachedProperty
(我不太了解附加属性的工作原理,但据我所见,我应该有一个 ContentControl
节点,我不...)但似乎没有什么是我需要的。
所以,回顾一下:我有一个 ListView,它为每个 ListViewItem
定义了一个 DataTemplate
,其中包含另一个 DataTemplate
,需要根据 ListViewItem
对象。我设法用 ContentTemplateSelector
实现了这一点,但它是在开始时分配的,然后就再也没有改变过。
您可以尝试将 ContentPresenter
替换为具有 Style
的 ContentControl
以及设置 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>
我有一组具有不同呈现选项的对象:它们可以是简单文本、可编辑文本、组合框,或者是混合包(例如组合框,其中项目通常是文本,但带有特定值的图像)。
我设法通过在 ListViewItem.ItemTemplate
的 DataTemplate
内的 ContentPresenter
节点内使用 ContentTemplateSelector
来正确显示所有内容:
<ContentPresenter
Grid.Row="1"
Grid.Column="1"
Content="{Binding .}"
ContentTemplateSelector="{DynamicResource ResourceKey=RenderTemplateSelector}"/>
(请注意,所有内容都在 ListView.ItemTemplate
的 DataTemplate
内)
一切都很好,直到我更改上述 属性 的值并需要更改模板,例如从图像变为文本。 VM 确实正确更新了值,但 GUI 中没有任何反应。
环顾四周,有一些方法(使用 Converter
(绑定到 属性??),定义 Style
(我认为不相关,因为我必须显示不同的控件,而不是更改同一控件的属性),使用 AttachedProperty
(我不太了解附加属性的工作原理,但据我所见,我应该有一个 ContentControl
节点,我不...)但似乎没有什么是我需要的。
所以,回顾一下:我有一个 ListView,它为每个 ListViewItem
定义了一个 DataTemplate
,其中包含另一个 DataTemplate
,需要根据 ListViewItem
对象。我设法用 ContentTemplateSelector
实现了这一点,但它是在开始时分配的,然后就再也没有改变过。
您可以尝试将 ContentPresenter
替换为具有 Style
的 ContentControl
以及设置 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>