我正在尝试在网格内的列表框上使用 ItemTemplateSelector,我在另一个文件上创建该列表框,以便稍后由 MainWindow 调用。
这是我的 DataTemplateSelector 代码
public class TemplateSelector : DataTemplateSelector
{
public override DataTemplate SelectTemplate(object item, DependencyObject container)
{
FrameworkElement element = container as FrameworkElement;
if (element != null && item != null && item is myClass)
{
myClass agg = item as myClass;
if(agg.myType == a)
{
return element.FindResource("greenItemTemplate") as DataTemplate;
}
else if (agg.myType == b)
{
return element.FindResource("yellowItemTemplate") as DataTemplate;
}
else if (agg.myType == c)
{
return element.FindResource("redItemTemplate") as DataTemplate;
}
}
return null;
}
}
这是我的xml
<Grid x:Class="NS.Views.ListView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:c="clr-namespace:NS.Commons"
DataContext="{Binding}">
<Grid.Resources>
<c:myConverter x:Key="converter" />
<c:TemplateSelector x:Key="borderSelector" />
<DataTemplate x:Key="greenItemTemplate">
<Border BorderThickness="3" BorderBrush="Green">
<StackPanel HorizontalAlignment="Stretch">
<TextBlock Text="{Binding Path=GroupName}"/>
<TextBlock Text="{Binding Path=myType}"/>
</StackPanel>
</Border>
</DataTemplate>
<DataTemplate x:Key="redItemTemplate">
<Border BorderThickness="3" BorderBrush="Red">
<StackPanel HorizontalAlignment="Stretch">
<TextBlock Text="{Binding Path=GroupName}"/>
<TextBlock Text="{Binding Path=myType}"/>
</StackPanel>
</Border>
</DataTemplate>
<DataTemplate x:Key="yellowItemTemplate">
<Border BorderThickness="3" BorderBrush="Yellow">
<StackPanel HorizontalAlignment="Stretch">
<TextBlock Text="{Binding Path=GroupName}"/>
<TextBlock Text="{Binding Path=myType}"/>
</StackPanel>
</Border>
</DataTemplate>
</Grid.Resources>
<ListBox ItemsSource="{Binding myCollectionOfMyClassObjects}"
Name="listBox1"
HorizontalContentAlignment="Stretch"
ItemTemplateSelector="{StaticResource borderSelector}"
>
</ListBox>
但是,虽然绑定工作正常(未格式化的对象列表出现在列表中),但 ItemTemplateSelector 并未调用 TemplateSelector 方法。我在方法的开头放置了一个断点,它从未被调用过。
有谁知道可能是什么问题?