使用兩個DataTemplates協同工作可以輕鬆構建您所需的內容:外部DataTemplate只需將DataContext設置爲inner DataTemplate,如下所示:
<DataTemplate x:Key="DisplayTemplate">
<Border ...>
<TextBlock Text="{Binding}" ... />
</Border>
</DataTemplate>
<DataTemplate x:Key="CellTemplate">
<ContentPresenter Content="{Binding FirstName}"
ContentTemplate="{StaticResource DisplayTemplate}" />
</DataTemplate>
唯一棘手的是在GridViewColumn上設置它。我將與附加屬性做到這一點,讓你寫:
<GridViewColumn
my:GVCHelper.DisplayPath="FirstName"
my:GVCHelper.Template="{StaticResource DisplayTemplate}" />
或等價代碼:
var col = new GridViewColumn();
GVCHelper.SetDisplayPath(col, "FirstName");
GVCHelper.SetTemplate(col, (DataTemplate)FindResource("DisplayTemplate"));
無論這些會導致名爲「DisplayTemplate」的DataTemplate中被用於顯示姓在列中。
助手類將被實現爲:
public class GVCHelper : DependencyObject
{
public static string GetDisplayPath(DependencyObject obj) { return (string)obj.GetValue(DisplayPathProperty); }
public static void SetDisplayPath(DependencyObject obj, string value) { obj.SetValue(DisplayPathProperty, value); }
public static readonly DependencyProperty DisplayPathProperty = DependencyProperty.RegisterAttached("DisplayPath", typeof(string), typeof(GVCHelper), new PropertyMetadata
{
PropertyChangedCallback = (obj, e) => Update(obj)
});
public static DataTemplate GetTemplate(DependencyObject obj) { return (DataTemplate)obj.GetValue(TemplateProperty); }
public static void SetTemplate(DependencyObject obj, DataTemplate value) { obj.SetValue(TemplateProperty, value); }
public static readonly DependencyProperty TemplateProperty = DependencyProperty.RegisterAttached("Template", typeof(DataTemplate), typeof(GVCHelper), new PropertyMetadata
{
PropertyChangedCallback = (obj, e) => Update(obj)
});
private static void Update(DependencyObject obj)
{
var path = GetDisplayPath(obj);
var template = GetTemplate(obj);
if(path!=null && template!=null)
{
var factory = new FrameworkElementFactory(typeof(ContentPresenter));
factory.SetBinding(ContentPresenter.ContentProperty, new Binding(path));
factory.SetValue(ContentPresenter.ContentTemplateProperty, template);
obj.SetValue(GridViewColumn.CellTemplateProperty,
new DataTemplate { VisualTree = factory };
}
}
}
它是如何工作的:每當這兩種屬性集,一個新的DataTemplate構造和GridViewColumn.CellTemplate屬性更新。