【问题标题】:How do I bind to the SelectedItem property in a ControlTemplate?如何绑定到 ControlTemplate 中的 SelectedItem 属性?
【发布时间】:2009-04-21 13:16:36
【问题描述】:

考虑以下控件/模板

<my:ExpandingListBox Margin="0,2,0,0" x:Name="TagSearchListBox">
    <my:ExpandingListBox.Template>
        <ControlTemplate TargetType="{x:Type my:ExpandingListBox}">
            <Border Name="MyBorder" BorderThickness="2" BorderBrush="Black">
                <Grid>
                    <TextBlock Name="MySelectionInfo" Background="White" Text="{TemplateBinding SelectedItem}"/>
                    <ScrollViewer Name="MyScrollViewer" HorizontalScrollBarVisibility="Hidden" Opacity="0" VerticalAlignment="Stretch" HorizontalAlignment="Stretch" VerticalScrollBarVisibility="Hidden">
                        <ItemsPresenter Name="MyItemsPresenter"/>
                    </ScrollViewer>
                </Grid>
            </Border>
        </ControlTemplate>
    </my:ExpandingListBox.Template>
</my:ExpandingListBox>

基本上,当 IsMouseOver 为 true 时,还有其他触发器/资源会导致控件展开/折叠。当控件折叠时,我希望 TextBlock "MySelectionInfo" 显示所选项目的文本;当它展开时,我希望像平常一样显示项目列表。有没有办法抓取所选项目的文本并将其显示在纯 XAML 的 TextBlock 中?

Setting Text="{TemplateBinding SelectedItem}" 运行,但不显示任何内容。

编辑(解决方案):

<TextBlock Name="MySelectionInfo" Background="White">
    <TextBlock.Text>
        <Binding Path="SelectedItem.Name">
            <Binding.RelativeSource>
                <RelativeSource Mode="FindAncestor" AncestorType="{x:Type my:ExpandingListBox}"/>
            </Binding.RelativeSource>
        </Binding>
    </TextBlock.Text>
</TextBlock>

“.Name”是我正在显示的项目类型的已知属性。

【问题讨论】:

    标签: wpf data-binding xaml controltemplates


    【解决方案1】:

    是否可以改为使用RelativeSource 进行绑定?也许是这样的:

    <TextBlock Name="MySelectionInfo" Background="White"
        Text="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type my:ExpandingListBox}}}" />
    

    【讨论】:

    • 效果很好!见上面的解决方案:)
    猜你喜欢
    • 1970-01-01
    • 2013-02-22
    • 2021-02-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多