0

I have a typical edit form (user control), with several input boxes. I need a ListBox which must show right below the TextBox with current focus, so it needs to move dynamically. I tried some binding, but nothing happens

<local:MyList x:Name="myList"
       Canvas.Left="{Binding (FocusManager.FocusedElement).Canvas.Left,RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type UserControl}}}"
       Canvas.Top="{Binding (FocusManager.FocusedElement).Canvas.Bottom,RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type UserControl}}}"
/>
4

1 回答 1

1

Use a Popup as it gives you facility to show it where you want. Its Placement = Bottom will show it exactly below the PlacementTarget.

Handle GotFocus, and LostFocus of TextBox.

        <TextBox Grid.Column="1" HorizontalAlignment="Left" Height="23" Margin="10,19,0,0" TextWrapping="Wrap" Text="TextBox" VerticalAlignment="Top" Width="120" GotFocus="TextBox_GotFocus_1" LostFocus="TextBox_LostFocus_1"/>
        <TextBox Grid.Column="1" HorizontalAlignment="Left" Height="23" Margin="10,57,0,0" TextWrapping="Wrap" Text="TextBox" VerticalAlignment="Top" Width="120" GotFocus="TextBox_GotFocus_1" LostFocus="TextBox_LostFocus_1"/>
        <TextBox Grid.Column="1" HorizontalAlignment="Left" Height="23" Margin="10,96,0,0" TextWrapping="Wrap" Text="TextBox" VerticalAlignment="Top" Width="120"/>
        <TextBox Grid.Column="1" HorizontalAlignment="Left" Height="23" Margin="10,136,0,0" TextWrapping="Wrap" Text="TextBox" VerticalAlignment="Top" Width="120" GotFocus="TextBox_GotFocus_1" LostFocus="TextBox_LostFocus_1"/>
        <TextBox Grid.Column="1" HorizontalAlignment="Left" Height="23" Margin="10,174,0,0" TextWrapping="Wrap" Text="TextBox" VerticalAlignment="Top" Width="120"/>

        <Popup Placement="Bottom" x:Name="LsbPopup">
            <ListBox>
                <ListBoxItem>item1</ListBoxItem>
                <ListBoxItem>item1</ListBoxItem>
                <ListBoxItem>item1</ListBoxItem>
                <ListBoxItem>item1</ListBoxItem>
                <ListBoxItem>item1</ListBoxItem>
                <ListBoxItem>item1</ListBoxItem>
                <ListBoxItem>item1</ListBoxItem>
            </ListBox>
        </Popup>

Handlers :

private void TextBox_GotFocus_1(object sender, RoutedEventArgs e)
{
    LsbPopup.PlacementTarget = sender as TextBox;
    LsbPopup.IsOpen = true;
}

private void TextBox_LostFocus_1(object sender, RoutedEventArgs e)
{
    LsbPopup.IsOpen = false;
}
于 2016-10-04T15:43:48.517 回答