【问题标题】:Implementing EventHandlers within ViewModel with MVVM WPF使用 MVVM WPF 在 ViewModel 中实现 EventHandlers
【发布时间】:2013-01-16 01:17:53
【问题描述】:

我有一个组合框:

<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”进行了一些错误处理。如果用户重新选择相同的 ComboBoxItem,我希望发生这种情况,除非选择了不同的列表项,否则它会触发 OnPropertyChanged。

以上绑定导致错误

不能在 'AddLostFocusHandler' 属性上设置“绑定” 键入“组合框”。只能在 DependencyProperty 上设置“绑定” 一个 DependencyObject。

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

【问题讨论】:

    标签: wpf mvvm


    【解决方案1】:

    乔希的回答对我来说用了不同的命名空间:

    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>
    

    【讨论】:

      【解决方案2】:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-11-10
        • 2019-05-29
        • 2020-05-19
        • 2013-01-02
        • 1970-01-01
        • 2013-09-29
        相关资源
        最近更新 更多