簡體   English   中英

WPF ControlTemplate和DataTemplate

[英]WPF ControlTemplate AND DataTemplate

我有ListView ,我想將自定義ControlTemplate應用於它的項目。 它的定義如下:

<ListView ItemsSource="{Binding MyAwesomeItems}" ...

MyAwesomeItems擁有不同的類。 所以我心想:“好吧,你好,DataTemplates。”

為了使包含的項看起來像我想要的那樣,我已經定義了一個這樣的ControlTemplate

<ListView.ItemContainerStyle>
  <Style TargetType="ListViewItem">
    <Setter Property="Template">
      <Setter.Value>
        <ControlTemplate TargetType="ListViewItem">
          <Border><ContentControl Content="{TemplateBinding Content}"/></Border>
        </ControlTemplate>            
      </Setter.Value>
    </Setter>
  </Style>
</ListView.ItemContainerStyle>

我使用ContentControl與Binding到TemplateBinding Content 我希望WPF會在ContentControl插入我的項目,使用我為其定義的任何DataTemplate。

但相反,看起來WPF只使用項.ToString()並且不應用任何DataTemplates。 這是預期的行為嗎?

我想要實現的是:擁有一個項目列表, 每個項目容器看起來都是我想要的,並且該容器的內容來自DataTemplate。

ContentControlControlTemplate ,通常使用空的ContentPresenter標記。 在你的情況下:

<ControlTemplate TargetType="ListViewItem">
    <Border>
        <ContentPresenter/>
    </Border>
</ControlTemplate>

ContentPresenter具有ContentSource屬性,默認為“Content”並設置所有必需的屬性( ContentContentTemplate等)。

詳情請見此處

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM