从自定义视图设置ListViewItem的ContentTemplate

问题描述 投票:1回答:1

我为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”)

wpf xaml listview data-binding view
1个回答
0
投票
public class CustomListView : ListView
{
  static CustomListView()
  {        
    DefaultStyleKeyProperty.OverrideMetadata(typeof(CustomListView), new 
    FrameworkPropertyMetadata(typeof(CustomListView)));
  }

  protected override DependencyObject GetContainerForItemOverride()
  {
      return new CustomListViewItem();
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.