TextBoxPopupBehavior控件
功能說明
一個用于 WPF TextBox 的附加行為,實現 TextBox 與 Popup 控件的聯動效果:
-
自動彈出/關閉:
- TextBox 獲得焦點時自動打開關聯的 Popup
- TextBox 失去焦點時自動關閉關聯的 Popup
-
點擊外部關閉:
- 點擊 TextBox 和 Popup 外部區域時關閉 Popup
-
焦點狀態處理:
- 解決 TextBox 保持焦點但 Popup 關閉后的重新觸發問題
核心代碼解析
// 解決在 TextBox 外其他地方點擊時,僅關閉 Popup,但是 TextBox 還是 Focused 狀態,導致再點擊進來時不會觸發彈出 Popup
private void AssociatedObject_PreviewMouseLeftButtonDown(object sender, System.Windows.Input.MouseButtonEventArgs e) {
if (AssociatedObject?.IsFocused == true && Popup != null && !Popup.IsOpen) {
Popup.IsOpen = true;
}
}
private void Window_PreviewMouseDown(object sender, System.Windows.Input.MouseButtonEventArgs e) {
if (Popup == null || !Popup.IsOpen || AssociatedObject == null || _parentWindow == null) { return; }
Point position = e.GetPosition(null);
Rect textBoxRect = new Rect(AssociatedObject.TranslatePoint(new Point(0, 0), _parentWindow), AssociatedObject.RenderSize);
Rect popupRect = new Rect(Popup.TranslatePoint(new Point(0, 0), _parentWindow), Popup.RenderSize);
if (!textBoxRect.Contains(position) && !popupRect.Contains(position)) {
Popup.SetCurrentValue(Popup.IsOpenProperty, false);
}
}
使用方法
<TextBox x:Name="SearchBox"
Width="400"
Height="30"
Text="{Binding ElementName=list, Path=SelectedItem.Content}">
<hc:Interaction.Behaviors>
<controls:TextBoxPopupBehavior Popup="{Binding ElementName=SuggestionsPopup}" />
</hc:Interaction.Behaviors>
</TextBox>
<Popup x:Name="SuggestionsPopup"
Placement="Bottom"
PlacementTarget="{Binding ElementName=SearchBox}"
StaysOpen="True">
<Border Background="White"
BorderBrush="Gray"
BorderThickness="1">
<ListBox x:Name="list"
Width="200"
Height="150">
<ListBoxItem>選項1</ListBoxItem>
<ListBoxItem>選項2</ListBoxItem>
<ListBoxItem>選項3</ListBoxItem>
</ListBox>
</Border>
</Popup>
注意事項
- 確保 Popup 的 PlacementTarget 正確綁定
- 在 MVVM 模式下可通過綁定設置 Popup 屬性
- 控件卸載時會自動清理事件監聽
文章作者:Memento
博客地址:http://www.rzrgm.cn/Memento/
版權聲明:Memento所有文章遵循創作共用版權協議,要求署名、非商業、保持一致。在滿足創作共用版權協議的基礎上可以轉載,但請以超鏈接形式注明出處。
博客地址:http://www.rzrgm.cn/Memento/
版權聲明:Memento所有文章遵循創作共用版權協議,要求署名、非商業、保持一致。在滿足創作共用版權協議的基礎上可以轉載,但請以超鏈接形式注明出處。

浙公網安備 33010602011771號