WPF - 基于类型的对象列表模板化

WPF - Templatize List of Objects Based on Their Type

我有一个列表对象(PropertyBase 是带有 KeyValue 属性 的基本类型),我想以某种方式向用户显示表格格式。基于对象类型,我想在不同的控件之间切换。假设 intdouble 值以 Label 表示,而 string 值可通过 TextBox 编辑。同样,我想为 enum 值显示 ComboBox

到目前为止,我已经阅读了有关 DataTemplates、ContentPresenters 的内容,并提出了以下 xaml 代码片段。但是,下面的模板显示对象的类型 (PropertyBase[Int64]PropertyBase[String]) 而不是它的值。这有什么问题吗?

<ItemsControl ItemsSource="{Binding Path=Properties}">
    <ItemsControl.ItemTemplate>
        <DataTemplate DataType="models:PropertyBase">
            <Grid Margin="0,0,0,5">
                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="*"/>
                    <ColumnDefinition Width="*"/>
                </Grid.ColumnDefinitions>
                <Label Grid.Column="0" Content="{Binding Key}" />
                <ContentPresenter Grid.Column="1" Content="{Binding}">
                    <ContentPresenter.Resources>
                        <DataTemplate DataType="{x:Type system:Int64}">
                            <Label Content="{Binding}" />
                        </DataTemplate>
                        <DataTemplate DataType="{x:Type system:String}">
                            <TextBox Text="{Binding Value, Mode=TwoWay}" />
                        </DataTemplate>
                    </ContentPresenter.Resources>
                </ContentPresenter>
            </Grid>
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>

问题出在数据绑定上。 ContentPresenter 未正确绑定。 <ContentPresenter Grid.Column="1" Content="{Binding}"> 绑定到当前源 (ref)。当前源是 PropertyBase class,其中包含 KeyValueContentPresenter 试图通过调用 ToString 方法而不是使用 Value 来显示 PropertyBase class 我想展示。

使用 <ContentPresenter Grid.Column="1" Content="{Binding Path=Value}"> 解决问题。