locked
Dynamically change style in datatemplate element RRS feed

  • Question

  • Hello. 

    I have a listbox with custom datatemplate for listboxitem.

    Datatemplate contains grid with 5 textblocks.

    I want to do the following: When item is selected 4 textblocks are green and one is red. When item is not selected, all textblocks should be gray.

    How can i do this? I don't want to create 2 datatemplates, because they will be almost equal. 

    Can i in ListBoxTrigger somehow set foreground color (change style) to element in datatemplate? 

    Friday, December 17, 2010 1:38 PM

Answers

  • I think that was not i was looking for. Problem has been solved.

    I was setting DataTemplate to ListBoxItem.ContentTemplate and in style trigger setter i was setting foreground for listboxitem (so i can't make red color for one textblock).

    Working solution: use controltemplate for ListBoxItem.Template and in contenttemplate trigger setter, set to named textblock element custom property value (foreground).

    • Marked as answer by firevortex Friday, December 17, 2010 8:57 PM
    Friday, December 17, 2010 8:57 PM

All replies

  • Hello, Try this:

     

    <DataTemplate>
               <TextBlock Text="{Binding Path=SomeProperty}">
                    <TextBlock.Style>
                         <Style TargetType="{x:Type TextBlock}">
                              <Style.Triggers>

                                   <DataTrigger Binding="{Binding RelativeSource={RelativeSource Mode=FindAncestor,AncestorType={x:Type  ListBoxItem}},Path=IsSelected}" Value="True">
                                        <Setter Property="Foreground" Value="Red"/>
                                  </DataTrigger>
                       </Style.Triggers>
                    </Style>
               </TextBlock.Style>
    </TextBlock> </DataTemplate>

     

    Good Luck

    • Edited by HomeroThompson Friday, December 17, 2010 2:10 PM Bad Format
    Friday, December 17, 2010 2:08 PM
  • I think that was not i was looking for. Problem has been solved.

    I was setting DataTemplate to ListBoxItem.ContentTemplate and in style trigger setter i was setting foreground for listboxitem (so i can't make red color for one textblock).

    Working solution: use controltemplate for ListBoxItem.Template and in contenttemplate trigger setter, set to named textblock element custom property value (foreground).

    • Marked as answer by firevortex Friday, December 17, 2010 8:57 PM
    Friday, December 17, 2010 8:57 PM