我已经构建了一个 DataTemplateSelector,用于在地图上显示不同的图钉。我现在有以下 DataTemplate 可以按我想要的方式工作,除了它不是图钉而是显示在地图上的文本块。
<DataTemplate x:Key="pushpinSelector">
<my:Pushpin Location="{Binding Location}" Tap="Pushpin_Tap">
<my:Pushpin.Template>
<ControlTemplate>
<local:PushpinTemplateSelector Content="{Binding}">
<local:PushpinTemplateSelector.ClusterTemplate>
<DataTemplate>
<TextBlock Text="Cluster" Width="100" Foreground="YellowGreen"></TextBlock>
</DataTemplate>
</local:PushpinTemplateSelector.ClusterTemplate>
<local:PushpinTemplateSelector.PushpinTemplate>
<DataTemplate>
<TextBlock Text="Pushpin" Width="100" Foreground="Blue"></TextBlock>
</DataTemplate>
</local:PushpinTemplateSelector.PushpinTemplate>
</local:PushpinTemplateSelector>
</ControlTemplate>
</my:Pushpin.Template>
</my:Pushpin>
</DataTemplate>
我希望它也能以以下格式工作:
<DataTemplate x:Key="pushpinSelector">
<local:PushpinTemplateSelector Content="{Binding}">
<local:PushpinTemplateSelector.ClusterTemplate>
<DataTemplate>
<my:Pushpin Location="{Binding Location}" Content="{Binding Count}" Foreground="YellowGreen"></my:Pushpin>
</DataTemplate>
</local:PushpinTemplateSelector.ClusterTemplate>
<local:PushpinTemplateSelector.PushpinTemplate>
<DataTemplate>
<my:Pushpin Location="{Binding Location}" Foreground="Blue"></my:Pushpin>
</DataTemplate>
</local:PushpinTemplateSelector.PushpinTemplate>
</local:PushpinTemplateSelector>
</DataTemplate>
但是使用这个模板,它只在地图上显示 1 个黑色图钉。我对绑定做错了吗?我不明白为什么这不能以预期的方式工作。
根据@localjoost 的要求,datatemplateselector 的代码:
抽象类:
public abstract class DataTemplateSelector : ContentControl
{
public virtual DataTemplate SelectTemplate(
object item, DependencyObject container)
{
return null;
}
protected override void OnContentChanged(object oldContent, object newContent)
{
base.OnContentChanged(oldContent, newContent);
ContentTemplate = SelectTemplate(newContent, this);
}
}
以及抽象类的实现:
public class PushpinTemplateSelector : DataTemplateSelector
{
public DataTemplate ClusterTemplate
{
get;
set;
}
public DataTemplate PushpinTemplate
{
get;
set;
}
public override DataTemplate SelectTemplate(object item, DependencyObject container)
{
PushpinModel model = item as PushpinModel;
if (model.CurrentObject == null)
{
return ClusterTemplate;
}
else
{
return PushpinTemplate;
}
}
}
以及我如何在地图控件中使用 Datatemplate(在我的应用程序资源部分中定义):
<my:Map Height="624" HorizontalAlignment="Left" Name="map1" VerticalAlignment="Top" Width="468" CredentialsProvider="XXXXX"
ZoomLevel="13">
<my:MapItemsControl Name="pushPinModelsLayer" ItemsSource="{Binding PushpinModels}" ItemTemplate="{StaticResource pushpinSelector}" />
<my:Pushpin Name="myLocation" Template="{StaticResource MyLocationTemplate}"></my:Pushpin>
</my:Map>
据我所知,图钉选择器模板中没有火箭科学。