使用MVVM WPF在ViewModel中实现EventHandler

时间:2013-01-31 20:09:38

标签: wpf mvvm

我有一个ComboBox:

<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,因为我在setter中为ViewModel中的SelectedValue绑定“ConnectionString”执行了一些错误处理。我希望如果用户重新选择相同的ComboBoxItem,除非选择了不同的列表项,否则会触发OnPropertyChanged。

上述绑定导致错误

  

无法在'AddLostFocusHandler'属性上设置'绑定'   输入'ComboBox'。 '绑定'只能在DependencyProperty上设置   DependencyObject。

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

2 个答案:

答案 0 :(得分:3)

您需要包含对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>

答案 1 :(得分:0)

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>
相关问题