输入一个字符后WPF文本框失去焦点
本文关键字:文本 WPF 失去 焦点 字符 一个 输入 | 更新日期: 2023-09-27 17:53:48
我对WPF非常陌生。我被指派去修复一个bug。你知道为什么在搜索栏中输入一个字符后,文本框会失去焦点吗?我不知道该发哪个代码来帮助你们。
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition
Width="100" />
<ColumnDefinition />
</Grid.ColumnDefinitions>
<Label
Content="Model Name:" />
<TextBox
Grid.Column="1"
Text="{Binding Path=ModelName, UpdateSourceTrigger=PropertyChanged,
ValidatesOnDataErrors=True}"
IsReadOnly="{Binding IsLoading}"
Style="{StaticResource FieldTextBox}"
MaxLength="{Binding ModelNameMaxLength}">
<TextBox.InputBindings>
<KeyBinding
Key="Enter"
Command="vmdls:ModelManagerViewModel.EditModel" />
<KeyBinding
Key="Up"
Command="vmdls:ModelManagerViewModel.MoveSelectionUp"/>
<KeyBinding
Key="Down"
Command="vmdls:ModelManagerViewModel.MoveSelectionDown" />
</TextBox.InputBindings>
</TextBox>
</Grid>
private string _modelName;
public string ModelName
{
get { return _modelName; }
set
{
if (_modelName == value)
return;
_modelName = value;
RefreshModels();
}
}
private void RefreshModels()
{
if (ModelName.SafeTrim() == string.Empty)
Models = new ObservableCollection<string>();
else
{
IsLoading = true;
Models = new ObservableCollection<string>(new string[] { "Loading ..." });
var workerThread = new Thread(new ThreadStart(GetModelsInternal))
{ IsBackground = true };
workerThread.Start();
}
}
private void GetModelsInternal()
{
IWaitIndicator waitIndicator = null;
var dispatcher = View.ViewElement.Dispatcher;
dispatcher.Invoke(new ThreadStart(() =>
{
waitIndicator = View.GetService<IWaitIndicatorFactory>().CreateWaitIndicator();
}));
var newModels = new string[] { };
try
{
using (var proxy = new ModelSvcClient())
newModels = proxy.FindModelsByName(ModelName);
}
catch (Exception vx)
{
View.GetService<IDisplayMessage>().ShowErrorMessage(vx.Message);
}
dispatcher.Invoke(new ThreadStart(() =>
{
_models = new ObservableCollection<string>(newModels);
SelectedModelsItem = _models.FirstOrDefault();
waitIndicator.Dispose();
OnPropertyChanged(() => Models);
IsLoading = false;
}));
}
UpdateSourceTrigger设置为PropertyChanged,因此每次键入字符时,ModelName都会更新。我怀疑setter中可能有一些代码导致焦点丢失。你可以尝试将UpdateSourceTrigger更改为Explicit或LostFocus。
要找到后面的代码只需右键单击,并选择"查看代码"。然而,它很可能使用MVVM模式,因此将有另一个类包含视图的逻辑。尝试右键单击模型名称(在Text="{Binding Path=ModelName"中)并选择"Go To Definition"(我相信此功能仅在VS2013和更新版本中可用)。