见下文所有DataTemplates都有相同的前两个TextBlock
在fieldStringTemplate和fieldDateTemplate中,我想引用fieldTemplate,所以我不再重复这两个。
如何从DataTemplate引用DataTemplate?
真正的应用程序有更多模板和更多常见元素 在实际应用中,这些是实现Field的类 FieldTemplateSelector基于类。
<Window.Resources>
<local:FieldTemplateSelector x:Key="fieldTemplateSelector"/>
<DataTemplate x:Key="fieldTemplate">
<StackPanel>
<TextBlock Text="{Binding Path=Name}" />
<TextBlock Text="{Binding Path=DisplayValue}" />
</StackPanel>
</DataTemplate>
<DataTemplate x:Key="fieldStringTemplate">
<StackPanel>
<TextBlock Text="{Binding Path=Name}" />
<TextBlock Text="{Binding Path=DisplayValue}" />
<TextBox Text="{Binding Path=FieldValue}" />
</StackPanel>
</DataTemplate>
<DataTemplate x:Key="fieldDateTemplate">
<StackPanel>
<TextBlock Text="{Binding Path=Name}" />
<TextBlock Text="{Binding Path=DisplayValue}" />
<DatePicker SelectedDate="{Binding Path=FieldValue}" />
</StackPanel>
</DataTemplate>
</Window.Resources>
<Grid>
<ListBox ItemsSource="{Binding Path=Fields}"
ItemTemplateSelector="{StaticResource fieldTemplateSelector}"
HorizontalContentAlignment="Stretch">
</ListBox>
</Grid>
答案 0 :(得分:2)
在我看来,做这样的事情要好得多:
<DataTemplate x:Key="fieldStringTemplate">
<TextBox Text="{Binding Path=FieldValue}" />
</DataTemplate>
<DataTemplate x:Key="fieldDateTemplate">
<DatePicker SelectedDate="{Binding Path=FieldValue}" />
</DataTemplate>
<!-- and so on... -->
<DataTemplate x:Key="common">
<StackPanel>
<TextBlock Text="{Binding Path=Name}" />
<TextBlock Text="{Binding Path=DisplayValue}" />
<ContentPresenter Content="{Binding}"
ContentTemplateSelector="{StaticResource fieldTemplateSelector}"/>
</StackPanel>
</DataTemplate>
<ListBox ItemsSource="{Binding Path=Fields}"
ItemTemplate="{StaticResource common}"
HorizontalContentAlignment="Stretch">
</ListBox>