如何在当前焦点的控件旁边定位WPF控件?

时间:2016-10-04 15:24:49

标签: c# wpf wpf-positioning

我有一个典型的edit form (user control),有几个输入框。 我需要一个ListBox,它必须显示在当前焦点的TextBox下方,因此需要动态移动。 我尝试了一些绑定,但没有任何反应

<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}}}"
/>

1 个答案:

答案 0 :(得分:1)

使用Popup因为它可以让您在任何地方展示它。其Placement = Bottom会将其显示在PlacementTarget的正下方。

处理GotFocus的{​​{1}}和LostFocus

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>