使用 MVVM WPF 在 ViewModel 中实现事件处理程序



我有一个组合框:

<ComboBox x:Name="cbConnection"
                      ItemsSource="{Binding Source={StaticResource XmlConnectionList}, XPath=//ComboItem}"
                      DisplayMemberPath="Key"
                      SelectedValuePath="Value"
                      SelectedValue="{Binding Path=ConnectionString,ValidatesOnDataErrors=True,UpdateSourceTrigger=PropertyChanged}" 
                      Margin="{StaticResource ConsistentMargins}"
                      Validation.ErrorTemplate="{StaticResource TextBoxErrorTemplate}" Width="120"
                      LostFocus="{Binding Path=cbConnection_LostFocus}"/>

我正在尝试将 LostFocus 事件处理程序移动到 ViewModel,因为我在 ViewModel 中找到的 SelectedValue 绑定"ConnectionString"的 setter 中执行了一些错误处理。 我希望如果用户重新选择相同的 ComboBoxItem,除非选择了不同的列表项,否则会触发 OnPropertyChanged,我希望发生这种情况。

上述绑定导致错误

不能在 "AddLostFocusHandler" 属性上设置"绑定" 键入"组合框"。只能在依赖项属性上设置"绑定" 的依赖对象。

如何在 ViewModel 中选择 ComboBox 中的任何项时触发可重复代码,而不考虑用户的选择?

您需要包含对 System.Windows.Interactivity dll 的引用,但它看起来像这样:

xmlns:b="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"  
<ComboBox>
<b:Interaction.Triggers>
    <b:EventTrigger EventName="LostFocus">
    <b:InvokeCommandAction  Command="{Binding cbConnection_LostFocus}" CommandParameter="{Binding}"/>
     </b:EventTrigger>
 </b:Interaction.Triggers>
</ComboBox>

Josh 的答案对我在不同的命名空间中起作用:

xmlns:b="http://schemas.microsoft.com/expression/2010/interactivity"  
<ComboBox>
<b:Interaction.Triggers>
    <b:EventTrigger EventName="LostFocus">
    <b:InvokeCommandAction  Command="{Binding cbConnection_LostFocus}" CommandParameter="{Binding}"/>
     </b:EventTrigger>
 </b:Interaction.Triggers>
</ComboBox>

最新更新