I am using an editable ComboBox in wpf but when i try to set focus from C# code, it is only shows selection. but i want to go for edit option (cursor should display for user input).
+1
A:
You might try deriving from ComboBox and access the internal TextBox, like this:
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
}
}
In your code you would use it like this:
<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>
This solution slightly dangerous, however, because in upcoming versions of WPF, Microsoft might decide also to add a GotKeyboardFocus event handler (or similar event handlers), which might get in conflict in with the event handler in MyComboBox.
fmunkert
2010-06-03 08:09:15
+1
A:
You can try this code:
var textBox = (comboBox.Template.FindName("PART_EditableTextBox", comboBox) as TextBox);
if (textBox != null)
{
textBox.Focus();
textBox.SelectionStart = textBox.Text.Length;
}
Rikker Serg
2010-06-03 08:14:50
no code cited here is working.
RAJ K
2010-06-11 05:43:50