你真的让我明白了,我从来没有意识到这个问题的存在。我找到了一个解决方案,它可以在您不关心清除焦点组合的情况下使用。可能有更好的方法,但没有我能想到的。也许有人有其他解决方案。
首先,在您的项目中添加对Windows.System.Interactivity 的引用,并将其添加到您的 XAML:
xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
然后,将此代码添加到组合框:
<ComboBox ItemsSource="{DynamicResource ItemsCompColl}"
TextSearch.TextPath="ItemName" x:Name="cbItems"
SelectedValue="{Binding ItemId, UpdateSourceTrigger=PropertyChanged,
ValidatesOnDataErrors=True}" SelectedValuePath="ItemId"
Grid.IsSharedSizeScope="True">
<i:Interaction.Triggers>
<i:EventTrigger EventName="GotMouseCapture">
<i:InvokeCommandAction Command="{Binding ClearCombo}"
CommandParameter="{Binding ElementName=cbItems}"/>
</i:EventTrigger>
</i:Interaction.Triggers>
</ComboBox>
最后,让我们在 ouw View Model 中创建命令:
RelayCommand<System.Windows.Controls.ComboBox> _clearCombo;
public ICommand ClearCombo
{
get
{
if (_clearCombo == null)
{
_clearCombo = new RelayCommand<System.Windows.Controls.ComboBox>(this.ClearComboCommandExecuted,
param => this.ClearComboCommandCanExecute());
}
return _clearCombo;
}
}
private bool ClearComboCommandCanExecute()
{
return true;
}
private void ClearComboCommandExecuted(System.Windows.Controls.ComboBox cb)
{
cb.Text = "";
}
希望这对您的问题有所帮助。
编辑
好的,在@XAMlMAX 评论之后,我认为他是对的,这可以在代码后面轻松完成,并且在 MVVM 模式中可能会更好。只需将事件处理程序添加到组合框即可捕获GotMouseCapture:
<ComboBox ItemsSource="{DynamicResource ItemsCompColl}"
TextSearch.TextPath="ItemName" x:Name="cbItems"
SelectedValue="{Binding ItemId, UpdateSourceTrigger=PropertyChanged,
ValidatesOnDataErrors=True}" SelectedValuePath="ItemId"
Grid.IsSharedSizeScope="True"
GotMouseCapture="cbItems_GotMouseCapture" >
然后在视图后面的代码中:
private void cbItems_GotMouseCapture(object sender, MouseEventArgs e)
{
((ComboBox)sender).Text = "";
}
编辑 2
好吧,解决它的最后一个丑陋的想法。我一点也不喜欢它,但也许它可以解决你的问题。
首先,你必须订阅TextBoxBase.TextChanged事件:
<ComboBox ItemsSource="{DynamicResource ItemsCompColl}"
TextSearch.TextPath="ItemName" x:Name="cbItems"
SelectedValue="{Binding ItemId, UpdateSourceTrigger=PropertyChanged,
ValidatesOnDataErrors=True}" SelectedValuePath="ItemId"
Grid.IsSharedSizeScope="True"
TextBoxBase.TextChanged="cbItems_TextChanged" >
然后在后面的代码中添加这段代码:
private void cbItems_TextChanged(object sender, TextChangedEventArgs e)
{
string text = ((ComboBox)sender).Text;
((YourViewModel)this.DataContext).ItemId= text;
}
这样,您可以确保每当ComboBox 更改其文本时,您都会收到有关它的通知。这真的是可怕的代码,但我已经没有想法了......