写个wpf控件 combobox双击变成textbox
时间: 2024-10-31 09:04:37 浏览: 10
wpf_combobox_tree下拉树形控件
4星 · 用户满意度95%
在WPF中创建一个ComboBox(组合框),当用户双击时切换成TextBox(文本框),你可以这样做:
首先,在XAML中定义ComboBox和TextBox的基本结构,并设置ComboBox的IsEditable属性为True以便允许编辑:
```xml
<Window x:Class="YourNamespace.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<Grid>
<StackPanel>
<ComboBox x:Name="comboBox" IsEditable="True">
<ItemsControl ItemsSource="{Binding YourDataSource}" />
</ComboBox>
<TextBox x:Name="textBox" IsReadOnly="True"/>
</StackPanel>
</Grid>
</Window>
```
然后,在后台代码-behind(例如`MainWindow.xaml.cs`)中,添加事件处理以监听ComboBox的SelectionChanged事件并在双击时转换显示模式:
```csharp
using System.Windows;
using System.Windows.Controls;
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
comboBox.SelectionChanged += ComboBox_SelectionChanged;
}
private void ComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (comboBox.SelectedItem != null && comboBox.IsDropDownOpen)
{
textBox.Text = ((string)comboBox.SelectedItem).ToString();
textBox.Focus(); // 设置焦点到TextBox
}
}
private void comboBox_MouseDoubleClick(object sender, MouseButtonEventArgs e)
{
if (e.ChangedButton == MouseButton.Left)
{
comboBox.IsDropDownOpen = false;
textBox.IsEnabled = true; // 开启TextBox
comboBox.IsEnabled = false; // 阻止ComboBox输入
}
}
private void textBox_GotFocus(object sender, RoutedEventArgs e)
{
comboBox.IsEnabled = true; // 当TextBox获得焦点时,恢复ComboBox功能
}
private void textBox_LostFocus(object sender, RoutedEventArgs e)
{
if (string.IsNullOrWhiteSpace(textBox.Text))
{
comboBox.SelectedItem = null; // 如果TextBox为空,则清空ComboBox选择项
}
else
{
comboBox.ItemsSource = null; // 清空ItemsSource,直到用户再次选择
comboBox.Items.Add(textBox.Text); // 添加选中的文本作为新选项
}
textBox.IsEnabled = false; // TextBox失去焦点时禁用
}
}
```
阅读全文