如何绑定ControlTemplate中的SelectedItem属性?

时间:2009-04-21 13:16:37

标签: wpf data-binding xaml controltemplates

考虑以下控制/模板

<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中显示它?

设置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”是我正在显示的项目类型的已知属性。

1 个答案:

答案 0 :(得分:2)

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

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