4

Consider the following Control/Template

<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>

Basically, there are additional triggers/resources that cause the control to expand/collapse when IsMouseOver is true. When the control is collapsed, I'd like the TextBlock "MySelectionInfo" to display the selected item's text; when it's expanded, I'd like the list of items to be displayed like normal. Is there a way to grab the selected item's text and display it in the TextBlock in pure XAML?

Setting Text="{TemplateBinding SelectedItem}" runs, but doesn't display anything.

EDIT (Solution):

<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" is a known property of the type of item I'm displaying.

4

1 回答 1

3

使用 a 来绑定会起作用RelativeSource吗?也许是这样的:

<TextBlock Name="MySelectionInfo" Background="White"
    Text="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type my:ExpandingListBox}}}" />
于 2009-04-21T13:23:46.767 回答