如何定位WPF控件旁边的控件与当前焦点
本文关键字:控件 焦点 定位 WPF 何定位 | 更新日期: 2023-09-27 18:11:24
我有一个典型的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}}}"
/>
使用Popup
,因为它可以方便地在需要的地方显示它。它的Placement = Bottom
将显示它正好低于PlacementTarget
。
处理TextBox
的GotFocus
和LostFocus
。
<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>
处理器:
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;
}