代码之家  ›  专栏  ›  技术社区  ›  jeremyalan

基于复选框值设置itemtemplate

  •  1
  • jeremyalan  · 技术社区  · 16 年前

    我有一个包含复选框和列表框的数据模板。选中复选框后,我想更改列表框上的itemtemplate属性,以更改每个项的外观。

    现在,看起来是这样的:

    <DataTemplate DataType={x:Type MyViewModel}>
       <DockPanel>       
          <CheckBox DockPanel.Dock="Bottom"
                    Content="Show Details"
                    HorizontalAlignment="Right"
                    IsChecked="{Binding ShowDetails}" 
                    Margin="0 5 10 5" />
    
          <ListBox ItemsSource="{Binding Items}"
                   ItemTemplate="{StaticResource SimpleItemTemplate}"
                   Margin="10 0 10 5">
             <ListBox.Triggers>
                <DataTrigger Binding="{Binding ShowDetails}" Value="True">
                   <Setter Property="ItemTemplate"
                           Value="{StaticResource DetailedItemTemplate}" />
                </DataTrigger>
             </ListBox.Triggers>
          </ListBox>
       </DockPanel>
    </DataTemplate>
    

    但是,当我尝试编译时,会收到以下错误消息:

    无法将值“itemtemplate”分配给属性“property”。PropertyDescriptor值无效。

    在“ContentPresenter”类型上找不到静态成员“itemTemplateProperty”。

    我对wpf还不太熟悉,所以可能有些事情我不太了解?

    1 回复  |  直到 16 年前
        1
  •  2
  •   itowlson    16 年前

    您需要通过listbox样式而不是直接通过其triggers集合来完成此操作。frameworkelement的triggers集合只能包含eventtriggers(所以我很惊讶您的示例竟然抱怨这些属性!)。以下是您需要做的:

    <ListBox ItemsSource="{Binding Items}">
      <ListBox.Style>
        <Style TargetType="ListBox">
          <Setter Property="ItemTemplate" Value="{StaticResource SimpleItemTemplate}" />
          <Style.Triggers>
            <DataTrigger Binding="{Binding ShowDetails}" Value="True">
               <Setter Property="ItemTemplate"
                       Value="{StaticResource DetailedItemTemplate}" />
            </DataTrigger>
         </Style.Triggers>
       </Style>
      </ListBox.Style>
    </ListBox>