2010-06-03 33 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; 
     } 
    })); 

}