c# - ComboBox 选择完成 MVVM 后强制绑定(bind)更新

标签 c# wpf mvvm binding combobox

我在可编辑组合框和绑定(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 .
  • 当用户选择一个项目时,SelectedItemText已更新。
  • 当用户离开ComboBox时(失去焦点),Command被触发。
  • 当用户输入文本并打开下拉列表时,Command被触发。
  • 编辑:奇怪的是Command当它获得焦点时也会触发。

这是您想要的行为吗?

关于c# - ComboBox 选择完成 MVVM 后强制绑定(bind)更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27275376/

相关文章:

c# - 在 WPF/C# 和 Qt/C++ 之间进行选择

WPF 重复问题 (MVVM)

c# - 将 UWP 应用程序最小化到系统托盘

c# - 如何在实例化大量控件时不阻塞 UI

c# - 查找对象的唯一排列

wpf - 如何在 WPF 应用程序中使用 NLog 的 RichTextBox Target?

mvvm - HTML 中声明的剑道窗口如何打开?

WPF Prism 交互请求触发器 : Re-create View and ViewModel upon show

c# - 非事件窗口的 ToolTip.Show 不起作用

c# - MSChart插入、移动、删除点