我在WPF中有可编辑的组合框,我想从C#设置焦点,
我使用的是Combobox.Focus(),但它只显示了选择,但我想要编辑选项,用户可以在其中开始输入。
更新:计算出修复
最后,我将“加载”事件添加到Combobox中,并编写了下面的代码以获得焦点,而且效果很好。
private void LocationComboBox_Loaded(object sender, RoutedEventArgs e)
{
ComboBox cmBox = (System.Windows.Controls.ComboBox)sender;
var textBox = (cmBox.Template.FindName("PART_EditableTextBox",
cmBox) as TextBox);
if (textBox != null)
{
textBox.Focus();
textBox.SelectionStart = textBox.Text.Length;
}
}发布于 2015-07-17 19:55:18
尝试创建如下所示的焦点扩展,并将附加属性设置为文本框并将其绑定。
public static class FocusExtension
{
public static bool GetIsFocused(DependencyObject obj)
{
return (bool)obj.GetValue(IsFocusedProperty);
}
public static void SetIsFocused(DependencyObject obj, bool value)
{
obj.SetValue(IsFocusedProperty, value);
}
public static readonly DependencyProperty IsFocusedProperty =
DependencyProperty.RegisterAttached(
"IsFocused", typeof(bool), typeof(FocusExtension),
new UIPropertyMetadata(false, OnIsFocusedPropertyChanged));
private static void OnIsFocusedPropertyChanged(DependencyObject d,
DependencyPropertyChangedEventArgs e)
{
var uie = (UIElement)d;
if ((bool)e.NewValue)
{
OnLostFocus(uie, null);
uie.Focus();
}
}
private static void OnLostFocus(object sender, RoutedEventArgs e)
{
if (sender != null && sender is UIElement)
{
(sender as UIElement).SetValue(IsFocusedProperty, false);
}
}
}XAML
<TextBox Extension:FocusExtension.IsFocused="{Binding IsProviderSearchFocused}"/>发布于 2015-07-17 20:16:41
如果我正确理解了您的意思,您会遇到以下情况:您将焦点设置为ComboBox,并在可编辑区域内观察选定的文本,但是您希望它是空的,其中只有闪烁的插入符号。如果是这样,你可以这样做:
ComboBox.Focus();
ComboBox.Text = String.Empty;发布于 2015-07-18 12:27:56
看看这个。它可能对你有帮助
https://stackoverflow.com/questions/31483650
复制相似问题