首页 > 解决方案 > 如何根据对象属性动态更新 DataTemplate?

问题描述

我有一组具有不同呈现选项的对象:它们可以是简单文本、可编辑文本、组合框或事件混合包(如组合框,其中项目通常是文本但带有特定值的图像)。

我设法通过在以下节点内使用来正确ContentTemplateSelector显示ContentPresenter所有DataTemplate内容ListViewItem.ItemTemplate

<ContentPresenter 
    Grid.Row="1"
    Grid.Column="1"
    Content="{Binding .}"
    ContentTemplateSelector="{DynamicResource ResourceKey=RenderTemplateSelector}"/>

(请注意,一切都在DataTemplatea内ListView.ItemTemplate

一切都很好,直到我更改所述属性的值并需要更改模板,例如从图像变为文本。VM 确实正确更新了这些值,但 GUI 中没有任何反应。

环顾四周,有一些方法(使用 a Converter(绑定到哪个属性??),定义 a Style(我认为不相关,因为我必须显示不同的控件,而不是更改同一个控件的属性),使用AttachedProperty(我不'不太了解附加属性是如何工作的,但从我所见,我应该有一个ContentControl节点,但我没有......)但似乎没有什么我需要的。

所以,回顾一下:我有一个 ListView,它DataTemplate为每个ListViewItem包含另一个DataTemplate需要根据ListViewItem对象的属性进行更改的定义。我设法用 a 实现了这一点ContentTemplateSelector,但它是在开始时分配的,然后从未改变过。

标签: c#wpfxamldynamicdatatemplate

解决方案


您可以尝试将 替换为ContentPresenter具有设置ContentControlStyle数据触发器,例如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>

推荐阅读