我为ListView控件创建自定义视图。
public class CustomView: View{
//...
public DataTemplate ItemTemplate { get; set; }
//...
}
<CustomView x:Key="Custom">
<CustomView.ItemTemplate>
<DataTemplate>
</DataTemplate>
</CustomView.ItemTemplate>
</CustomView>
ListViewItem
的样式,我想从DataTemplate
上的CustomView.ItemTemplate
绑定ContentTemplate
。
<Style x:Key="{ComponentResourceKey TypeInTargetAssembly={x:Type CustomView}, ResourceId=CustomViewItem}"
TargetType="{x:Type ListViewItem}"
BasedOn="{StaticResource {x:Type ListBoxItem}}">
<Setter Property="ContentTemplate"
Value="{Binding Path=View.ItemTemplate,
RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ListView}}}" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type ListBoxItem}">
<Border x:Name="ItemBorder">
<ContentPresenter />
</Border>
</Setter.Value>
</Setter>
</Style>
<Style x:Key="{ComponentResourceKey TypeInTargetAssembly={x:Type CustomView}, ResourceId=CustomView}"
TargetType="{x:Type ListView}"
BasedOn="{StaticResource {x:Type ListBox}}">
</Style>
查看有效,但在VS的输出窗口中出现此错误:
找不到参考'RelativeSource的绑定源FindAncestor,AncestorType ='System.Windows.Controls.ListView',AncestorLevel ='1''。 BindingExpression:Path = View.ItemTemplate;DataItem = null;目标元素是'ListViewItem'(Name ='');目标属性为“ ContentTemplate”(类型为“ DataTemplate”)
public class CustomListView : ListView
{
static CustomListView()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(CustomListView), new
FrameworkPropertyMetadata(typeof(CustomListView)));
}
protected override DependencyObject GetContainerForItemOverride()
{
return new CustomListViewItem();
}
}