【问题标题】:Set ContentTemplate for ListViewItem from Custom View从自定义视图为 ListViewItem 设置 ContentTemplate
【发布时间】: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 的风格,我想将DataTemplateCustomView.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


【解决方案1】:
public class CustomListView : ListView
{
  static CustomListView()
  {        
    DefaultStyleKeyProperty.OverrideMetadata(typeof(CustomListView), new 
    FrameworkPropertyMetadata(typeof(CustomListView)));
  }

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-22
    • 2014-07-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多