开发者

Setting ItemTemplate based on CheckBox value

I have a DataTemplate which contains a CheckBox and ListBox. When the CheckBox is checked, I want to change the ItemTemplate property on the ListBox to change the appearance of each item.

Right now, it looks like this:

<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>

However, when I try to compile, I get the following error messages:

Value 'ItemTemplate' cannot be assigned to property 'Property'. Invalid PropertyDescriptor value.

and

Cannot find the static member 'ItemTemplateProperty' on the type 'ContentPresenter'.

I'm 开发者_JAVA技巧still fairly new to WPF, so perhaps there is something I'm not quite understanding?


You need to do this through the ListBox Style rather than directly through its Triggers collection. A FrameworkElement's Triggers collection can only contain EventTriggers (so I'm surprised your sample got as far as complaining about the properties!). Here's what you need to do:

<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>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜