我在可编辑组合框和绑定(bind)更新方面遇到了一些问题。目前我有一个 ComboBox,其 UpdateSourceTrigger=LostFocus 这是因为我需要等待用户完成输入内容,然后才能决定该值是否是新值(从而创建一个新值)。
不幸的是,我还有另一个功能,它要求绑定(bind)在值更改时也进行更新。也就是说,在这种情况下,LostFocus 对我来说没有什么好处。当在 ComboBox 中选择新值时,它不会导致 LostFocus 触发(显然)。所以我需要找到一种方法来强制更新绑定(bind)。
我已经研究了 SelectionChanged 并强制更新绑定(bind):
<i:EventTrigger EventName="SelectionChanged">
<i:InvokeCommandAction Command="{Binding ParentConversation.ViewModel.ComboSelectionChanged}" CommandParameter="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type controls:StoryForgeComboBox}}}"/>
</i:EventTrigger>
并更新后面代码中的绑定(bind),如下所示:
be = BindingOperations.GetBindingExpression(ele, ComboBox.TextProperty);
if (be != null)
{
be.UpdateSource();
}
不幸的是,我此时无法更新绑定(bind),因为该值尚未更改。请参阅此 stackoverflow 主题:ComboBox- SelectionChanged event has old value, not new value
有一个技巧,您可以使用 DropDownClosed 事件,然后更新绑定(bind),这可以工作,但如果您使用从不打开组合框的向上/向下箭头键,则不起作用。另外,连接 KeyUp 和 KeyDown 还为时过早。绑定(bind)尚无法更新。
所以我的问题是,什么时候是说“嘿组合框先生,您现在可以更新您的绑定(bind)”的好时机。
干杯。
最佳答案
您可以更改 SelectionChanged
事件触发LostFocus
:
<ComboBox
IsEditable="True"
ItemsSource="{Binding Items}"
SelectedItem="{Binding SelectedItem}"
Text="{Binding Text, UpdateSourceTrigger=PropertyChanged}">
<i:Interaction.Triggers>
<i:EventTrigger
EventName="LostFocus">
<i:InvokeCommandAction
Command="{Binding Command}" />
</i:EventTrigger>
</i:Interaction.Triggers>
</ComboBox>
- 当用户键入时,
Text
已更新。 - 当用户键入
ComboBox
时在Items
中找到匹配项,SelectedItem
已更改。 - 当用户键入时,
ComboBox
未找到匹配项且之前已选择项目,SelectedItem
设置为null
. - 当用户选择一个项目时,
SelectedItem
和Text
已更新。 - 当用户离开
ComboBox
时(失去焦点),Command
被触发。 - 当用户输入文本并打开下拉列表时,
Command
被触发。 - 编辑:奇怪的是
Command
当它获得焦点时也会触发。
这是您想要的行为吗?
关于c# - ComboBox 选择完成 MVVM 后强制绑定(bind)更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27275376/