1
votes

I create custom View for ListView control.

public class CustomView: View{
//...
        public DataTemplate ItemTemplate { get; set; }
//...
}


<CustomView x:Key="Custom">
    <CustomView.ItemTemplate>
        <DataTemplate>
        </DataTemplate>
    </CustomView.ItemTemplate>
</CustomView>

In style for ListViewItem I would like bind DataTemplate from CustomView.ItemTemplate on 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>

View works but in output window in VS I get this error:

Cannot find source for binding with reference 'RelativeSource FindAncestor, AncestorType='System.Windows.Controls.ListView', AncestorLevel='1''. BindingExpression:Path=View.ItemTemplate; DataItem=null; target element is 'ListViewItem' (Name=''); target property is 'ContentTemplate' (type 'DataTemplate')

1
I create custom View for ListView control - why are you doing that? subclassing WPF UI elements is discouraged unless you have a strong reason...Federico Berasategui

1 Answers

0
votes
public class CustomListView : ListView
{
  static CustomListView()
  {        
    DefaultStyleKeyProperty.OverrideMetadata(typeof(CustomListView), new 
    FrameworkPropertyMetadata(typeof(CustomListView)));
  }

  protected override DependencyObject GetContainerForItemOverride()
  {
      return new CustomListViewItem();
  }
}