[英]How to align Text in DataTemplate choosen by a DataTemplateSelector?
I am trying to align text in a DataTemplate of a ListBox depending on the choice of the DataTemplateSelector.我试图根据 DataTemplateSelector 的选择在 ListBox 的 DataTemplate 中对齐文本。
What I want is something like this:我想要的是这样的:
And tried to use a DataTemplateSelector并尝试使用 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.我也试过 HorizontalAlignment,也没有用。 How to accomplish the effect?
效果如何实现?
One solution is to change the ListBoxItem
style so that its HorizontalContentAlignment
is Stretch
:一种解决方案是更改
ListBoxItem
样式,使其HorizontalContentAlignment
为Stretch
:
<ListBox.ItemContainerStyle>
<Style TargetType="ListBoxItem">
<Setter Property="HorizontalContentAlignment" Value="Stretch" />
</Style>
</ListBox.ItemContainerStyle>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.