【问题标题】:Force Binding update after ComboBox selection has completed MVVM组合框选择完成 MVVM 后强制绑定更新
【发布时间】:2015-02-01 05:33:45
【问题描述】:

我在使用可编辑组合框和更新绑定时遇到了一些问题。目前我有一个 ComboBox,它的 UpdateSourceTrigger=LostFocus 这是因为我需要等待用户完成输入,然后才能确定该值是否为新值(从而创建一个新值)。

不幸的是,我还有另一个功能,它需要在值更改时更新绑定。 Aka,在这种情况下,LostFocus 对我没有好处。在 ComboBox 中选择一个新值不会导致 LostFocus 触发(显然)。所以我需要找到一种方法来强制更新绑定。

我查看了 SelectionChanged 并强制更新绑定:

    <i:EventTrigger EventName="SelectionChanged">
        <i:InvokeCommandAction Command="{Binding ParentConversation.ViewModel.ComboSelectionChanged}" CommandParameter="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type controls:StoryForgeComboBox}}}"/>
    </i:EventTrigger>

并像这样在后面的代码中更新绑定:

be = BindingOperations.GetBindingExpression(ele, ComboBox.TextProperty);
if (be != null)
{
    be.UpdateSource();
}

很遗憾,我现在无法更新绑定,因为值尚未更改。请参阅此 stackoverflow 主题:ComboBox- SelectionChanged event has old value, not new value

有一个技巧,您可以使用 DropDownClosed 事件然后更新绑定,这有效,但如果您使用永远不会打开 ComboBox 的向上/向下箭头键则不起作用。还挂钩到 KeyUp 和 KeyDown 还为时过早。绑定还不能更新。

所以我的问题是,什么时候是说“嘿,组合框先生,您现在可以更新绑定”的好时机。

干杯。

【问题讨论】:

  • So I need to find a way to force update the binding - 你到底想达到什么目的?在 MVVM 中,ViewModel 实现了INotifyPropertyChanged,因此,如果您更改属性值(或显式更改属性值),则从源更新隐含地发生,而在其他方向,源更新是(如您所说)UpdateSourceTrigger=ValueChanged。哪一个是你的问题?

标签: c# wpf mvvm binding combobox


【解决方案1】:

您可以将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 会更新。
  • 当用户键入并且ComboBoxItems 中找到匹配项时,SelectedItem 会更改。
  • 当用户键入时,ComboBox 找不到匹配项,并且之前选择了一个项目,SelectedItem 设置为 null
  • 当用户选择一个项目时,SelectedItemText 都会更新。
  • 当用户离开ComboBox(失去焦点)时,Command被触发。
  • 当用户输入文本并打开下拉列表时,Command 被触发。
  • 编辑:奇怪的是,Command 在获得焦点时也会被触发。

这是你想要的行为吗?

【讨论】:

  • 我从未考虑尝试同时绑定文本和选定项。这可能行得通!
  • 非常感谢。奥卡姆剃刀。总是。
  • 正如 hantoun 所说,在编辑模式下,您必须小心使用 ComboBox 的 LostFocus 事件。当 ComboBox 最初获得焦点时,它会将焦点赋予其中的文本框,从而导致 ComboBox 引发 LostFocus 事件。您可以通过将 LostFocus 触发器直接添加到 ComboBox 的文本框 var textbox = (TextBox)comboBox.Template.FindName("PART_EditableTextBox", combobox); textbox.LostFocus += (sender, args) =&gt; viewModel.Command.Execute(); 来解决这个问题
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-12-17
  • 1970-01-01
  • 1970-01-01
  • 2011-02-21
  • 2011-06-13
  • 2018-06-12
  • 2015-09-15
相关资源
最近更新 更多