2010-06-03 32 views

回答

3

你可以尝试从ComboBox中派生并访问内部文本框,如下所示:

public class MyComboBox : ComboBox 
{ 
    TextBox _textBox; 

    public override void OnApplyTemplate() 
    { 
     base.OnApplyTemplate(); 

     _textBox = Template.FindName("PART_EditableTextBox", this) as TextBox; 
     if (_textBox != null) 
     { 
      _textBox.GotKeyboardFocus += _textBox_GotFocus; 
      this.Unloaded += MyComboBox_Unloaded; 
     } 
    } 

    void MyComboBox_Unloaded(object sender, System.Windows.RoutedEventArgs e) 
    { 
     _textBox.GotKeyboardFocus -= _textBox_GotFocus; 
     this.Unloaded -= MyComboBox_Unloaded; 
    } 

    void _textBox_GotFocus(object sender, System.Windows.RoutedEventArgs e) 
    { 
     _textBox.Select(_textBox.Text.Length, 0); // set caret to end of text 
    } 

} 

在你的代码会使用这样的:

<Window x:Class="EditableCbox.Window1" 
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    xmlns:local="clr-namespace:EditableCbox" 
    Title="Window1" Height="300" Width="300"> 
    ... 
     <local:MyComboBox x:Name="myComboBox" IsEditable="True" Grid.Row="0" Margin="4"> 
      <ComboBoxItem>Alpha</ComboBoxItem> 
      <ComboBoxItem>Beta</ComboBoxItem> 
      <ComboBoxItem>Gamma</ComboBoxItem> 
     </local:MyComboBox> 
    ... 
</Window> 

该解决方案略有危险,但是,因为在即将推出的WPF版本中,微软可能会决定添加一个GotKeyboardFocus事件处理程序(或类似的事件处理程序),它可能与MyComboBox中的事件处理程序发生冲突。上面我想出了一个稍微简单的解决方案

 var textBox = (comboBox.Template.FindName("PART_EditableTextBox", comboBox) as TextBox); 
     if (textBox != null) 
     { 
      textBox.Focus(); 
      textBox.SelectionStart = textBox.Text.Length; 
     } 
9

你可以试试这个代码。在构造函数或ContextChangedHandler代码正在等待控制,把着眼点UI元素

myComboBox.GotFocus += MyComboBoxGotFocus; 
myComboBox.Loaded += (o, args) => { myComboBox.Focus(); }; 

然后在焦点,甚至处理我选择所有从一开始的文字到底

之前加载
private void MyComboBoxGotFocus(object sender, RoutedEventArgs e) 
{ 
    var textBox = myComboBox.Template.FindName("PART_EditableTextBox", myComboBox) as TextBox; 
    if (textBox != null) 
     textBox.Select(0, textBox.Text.Length); 
} 

在xaml中,组合框是可编辑的。通过选择所有的文本时,用户键入基于Rikker SERG的回答是重置前值

<ComboBox x:Name="myComboBox" IsEditable="True" /> 
+1

这里没有引用任何代码正在工作。 – 2010-06-11 05:43:50

+2

@RAJK这段代码对我来说非常合适。它恰当地解决了首次显示窗口时需要关注可编辑组合框的问题。没有明确说明的是,您必须将代码放入包含可编辑组合框的窗口的Loaded事件中。 – 2011-10-24 19:00:55

+0

完美!解决了我很多很多的问题!非常感谢! – 2017-12-24 14:21:13

3

基于user128300的答案:

0

一个键,就可以使用该代码(之后的InitializeComponent)构造函数,并派遣它,而不是需要来创建自定义的控件或事件处理程序。

public NewMessageWindow() 
{ 
    InitializeComponent(); 

    Dispatcher.BeginInvoke(new Action(() => 
    { 
     var textBox = myComboBox.Template.FindName("PART_EditableTextBox", cbUsers) as TextBox; 
     if (textBox != null) 
     { 
      textBox.Focus(); 
      textBox.SelectionStart = textBox.Text.Length; 
     } 
    })); 

}