【发布时间】:2014-06-03 14:02:15
【问题描述】:
我为 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', 祖先级别='1''。 BindingExpression:Path=View.ItemTemplate; 数据项=空;目标元素是'ListViewItem'(名称='');目标 属性是“ContentTemplate”(类型“DataTemplate”)
【问题讨论】:
-
I create custom View for ListView control- 你为什么要这么做?不鼓励子类化 WPF UI 元素,除非您有strong原因...
标签: wpf xaml listview data-binding view