Wpf 将TextBlock绑定回ListBoxItem ItemSource

Wpf 将TextBlock绑定回ListBoxItem ItemSource,wpf,xaml,binding,styles,listboxitem,Wpf,Xaml,Binding,Styles,Listboxitem,我有一个ListBoxItem样式,我正在尝试修改它,以便在列表框变小时显示字符省略号。要做到这一点,我必须在代码中去掉ContentPresenter,并用TextBlock替换它。应用此属性的列表框都通过ItemSource属性绑定 这是我的密码 <Style x:Key="ListBoxItemStyle" TargetType="{x:Type ListBoxItem}"> <Setter Property="Background" Value="White"/

我有一个ListBoxItem样式,我正在尝试修改它,以便在列表框变小时显示字符省略号。要做到这一点,我必须在代码中去掉ContentPresenter,并用TextBlock替换它。应用此属性的列表框都通过ItemSource属性绑定

这是我的密码

<Style x:Key="ListBoxItemStyle" TargetType="{x:Type ListBoxItem}">
    <Setter Property="Background" Value="White"/>
    <Setter Property="Margin" Value="0,0,0,0"/>
    <Setter Property="Padding" Value="0,0,0,0"/>
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type ListBoxItem}">
                <Grid>
                    <Border x:Name="Bd" SnapsToDevicePixels="true">
                        <!-- Before this used to be ContentPresenter but I switched it to TextBlock to get it the TextTrimming property. I can't find the right way to bind the data though.-->
                        <TextBlock Text="{TemplateBinding DisplayMemberPath}" TextTrimming="CharacterEllipsis" HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}"
                                          SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}"
                                          VerticalAlignment="{TemplateBinding VerticalContentAlignment}"/>
                    </Border>
                    <Rectangle x:Name="HoverRectangle"
                               Stroke="{StaticResource Gold}"
                               StrokeDashCap="Square"
                               StrokeThickness="0"
                               SnapsToDevicePixels="True" />
                    <Rectangle x:Name="KeyboardFocusRectangle"
                               Height="Auto"
                               SnapsToDevicePixels="True"
                               Stroke="{StaticResource BrightBlue}"
                               StrokeDashCap="Square"
                               StrokeThickness="0" />
                </Grid>
                <ControlTemplate.Triggers>
                     <!-- Bunch of Triggers in here -->
                </ControlTemplate.Triggers>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>


我当前的文本块文本绑定(Text=“{TemplateBinding DisplayMemberPath}”)不工作。为了正常工作,绑定应该是什么

这里唯一合理的选择是假设ListBoxItem的数据上下文是一个字符串,或者可以这样显示:

<TextBlock Text="{Binding}" .../>

您已将“问题”隐藏在代码中-我建议您进行编辑。这实际上并没有解决我的问题,但它确实为我提供了指向正确方向的信息。我应该考虑为它创建一个数据模板。我做到了,它解决了问题。非常感谢。