I am trying to align text in a DataTemplate of a ListBox depending on the choice of the DataTemplateSelector.
What I want is something like this:
And tried to use a DataTemplateSelector
<DataTemplate x:Key="RequestTemplate" DataType="local:Message">
<TextBlock Text="{Binding Text}" Background="LightGreen" TextAlignment="Left" TextWrapping="Wrap"/>
</DataTemplate>
<DataTemplate x:Key="ResponseTemplate" DataType="local:Message" >
<TextBlock Text="{Binding Text}" Background="Yellow" TextAlignment="Right" TextWrapping="Wrap"/>
</DataTemplate>
<local:MesssageDataTemplateSelector x:Key="MessageDataTemplateSelector"
ResponseTemplate="{StaticResource ResponseTemplate}"
RequestTemplate="{StaticResource RequestTemplate}" />
The ListBox itself:
<ListBox ItemTemplateSelector="{StaticResource MessageDataTemplateSelector}" ItemsSource="{Binding Messages}" />
The colors are applied the alignment is not.
I also tried HorizontalAlignment, also not working. How to accomplish the effect?
One solution is to change the ListBoxItem
style so that its HorizontalContentAlignment
is Stretch
:
<ListBox.ItemContainerStyle>
<Style TargetType="ListBoxItem">
<Setter Property="HorizontalContentAlignment" Value="Stretch" />
</Style>
</ListBox.ItemContainerStyle>