C# 将Datatemplate与绑定类型关联
我有这样的代码,即使绑定类型似乎是LineRenderableSeriesViewModel,也始终显示默认的datatemplateC# 将Datatemplate与绑定类型关联,c#,wpf,C#,Wpf,我有这样的代码,即使绑定类型似乎是LineRenderableSeriesViewModel,也始终显示默认的datatemplate <ListBox ItemsSource="{Binding ElementName=ACList, Path=SelectedItem.seriesViewModels, Mode=OneWay}" IsSynchronizedWithCurrentItem="True">
<ListBox ItemsSource="{Binding ElementName=ACList, Path=SelectedItem.seriesViewModels, Mode=OneWay}" IsSynchronizedWithCurrentItem="True">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel>
<StackPanel.Resources>
<DataTemplate x:Key="Default" >
<Border BorderBrush="Red" BorderThickness="2" Background="Pink">
<TextBlock Text="{Binding}" Foreground="Red" FontWeight="Bold" Padding="5"/>
</Border>
</DataTemplate>
<DataTemplate x:Key="BindedTemplate1" >
<Border BorderBrush="Green" BorderThickness="2" CornerRadius="5">
<TextBlock Text="I'm asssociated to LineRenderableSeriesViewModel " Foreground="Green" FontWeight="Bold" Padding="5"/>
</Border>
</DataTemplate>
</StackPanel.Resources>
<!-- atempt to write type of object -->
<Label Content="{Binding}" ContentStringFormat="MyBindingType : {0}"></Label>
<!-- atempt to display the associated template -->
<ContentControl Content="{Binding}">
<ContentControl.Style>
<Style TargetType="ContentControl">
<Setter Property="ContentTemplate" Value="{StaticResource Default}"/>
<Style.Triggers>
<DataTrigger Binding="{Binding}" Value="LineRenderableSeriesViewModel">
<Setter Property="ContentTemplate" Value="{StaticResource BindedTemplate1}"/>
</DataTrigger>
</Style.Triggers>
</Style>
</ContentControl.Style>
</ContentControl>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
显示将显示viewmodel的rigth值,但它采用默认的datatemplate
我不知道会发生什么事?你可以做得容易得多。
只需使用属性
DataType
定义数据模板,绑定引擎将为您完成其余的工作
<ListBox ItemsSource="{Binding Path=ACList}" >
<ListBox.Resources>
<DataTemplate DataType="{x:Type local:Other}" >
<Border BorderBrush="Red" BorderThickness="2" Background="Pink">
<TextBlock Text="{Binding}" Foreground="Red" FontWeight="Bold" Padding="5"/>
</Border>
</DataTemplate>
<DataTemplate DataType="{x:Type local:LineRenderableSeriesViewModel}">
<Border BorderBrush="Green" BorderThickness="2" CornerRadius="5">
<TextBlock Text="I'm asssociated to LineRenderableSeriesViewModel " Foreground="Green" FontWeight="Bold" Padding="5"/>
</Border>
</DataTemplate>
</ListBox.Resources>
</ListBox>
只要记住将“local”与名称空间定义交换,如果当前项的值(而不是类型)是LineRenderableSeriesViewModel,那么类所在的名称空间定义将起作用。与这种奇怪的构造不同,应该有一组数据模板资源,这些资源的数据类型设置适当。不要明确设置ItemTemplate属性。或者,使用DataTemplateSelector。我确实更改了,但它仍然不处于活动状态。我认为该类型是数据绑定或类似的类型,但不是我真正等待的类型。我不知道如何签入标签,如果该类型是它应该删除的类型,它应该可以工作。是的,我使用了不同的技术,但它现在可以工作,因为有一个键已经准备好了谢谢