0
votes

I was trying to change list items appearance in dataTemplate but I had problem with changing a selected item look. I've found this question: Change WPF DataTemplate for ListBox item if selected

and i tried to create similar code as in the answer:

<DataTemplate x:Key="NoteTemplate">
        <Border Margin="5" BorderThickness="1" BorderBrush="Transparent" Background="#F3EBC2" CornerRadius="4">
            <Grid Margin="3" Width="395" MaxHeight="40">
                <Grid.RowDefinitions>
                    <RowDefinition />
                    <RowDefinition/>                        
                </Grid.RowDefinitions>
                <Grid Row="0" >
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition/>
                        <ColumnDefinition/>
                    </Grid.ColumnDefinitions>
                    <TextBlock Grid.Column="0" FontSize="15" FontFamily="Consolas" FontWeight="Bold" Text="{Binding Path=tytul}"/>
                    <TextBlock Grid.Column="1" FontSize="13" FontFamily="Consolas" FontStyle="Italic" HorizontalAlignment="Right" Text="{Binding Path=data_dodania}"/>
                </Grid>
                <TextBlock Grid.Row="1" FontSize="13" FontFamily="Consolas" Text="{Binding Path=tresc}"/>
            </Grid>
        </Border>
    </DataTemplate>



    <Style TargetType="{x:Type ListBoxItem}" x:Key="ListBoxItem">
        <Setter Property="ContentTemplate" Value="{StaticResource NoteTemplate}" />
        <Style.Triggers>
            <Trigger Property="IsSelected" Value="True">
                <Setter Property="ContentTemplate" Value="{StaticResource NoteTemplate}" />
            </Trigger>
        </Style.Triggers>
    </Style>

(I put the same template in trigger just to check if it works)

<ListBox Name="listBoxNotatki" Margin="10" ItemContainerStyle="{StaticResource ListBoxItem}" Background="Beige" BorderBrush="Orange" BorderThickness="3"/>

But then i got this error:

"Unable to cast object of type 'MS.Internal.NamedObject' to type 'System.Windows.DataTemplate'."

When I change StaticResource to DynamicResorce i get rid of this error but then the trigger in my style doesn't work (Selected item looks just like at the beginning).

1

1 Answers

0
votes

On the ListBox Control set the ItemTemplate to "NoteTemplate". ListBox is aware of it's SelectedItem.

In your case, I would write a DataTemplateSelector and use it on the ItemTemplateSelector of the Listbox for the before and after look.

This article does a good job explaining it: http://codepb.com/datatemplateselector-in-xaml-versatile-xaml-controls/