我是MVVM模式的新手,我必须在以下 View 中拦截已检查/未检查的操作

SendMessageView.xaml

<ListBox.ItemTemplate>
   <DataTemplate>
      <StackPanel>
         <CheckBox Checked="Specialita_Checked"
                Unchecked="Specialita_Unchecked"
                Content="{Binding Path=Item.Name}"
                IsChecked="{Binding RelativeSource={RelativeSource FindAncestor,
                            AncestorType={x:Type ListBoxItem}},
                            Path=IsSelected,Mode=TwoWay}"/>
      </StackPanel>
   </DataTemplate>
</ListBox.ItemTemplate>

SendMessageView.xaml.cs
private void Specialita_Checked(object sender, System.Windows.RoutedEventArgs e)
{
   var aSendMessageViewModel = (SendMessageViewModel)this.DataContext;
   if (aSendMessageViewModel != null)
   {
      var aCheckBox = (CheckBox)sender;
      aSendMessageViewModel.AddSpecialita(aCheckBox.Content.ToString());
   }
}

aSendMessageViewModel.cs内部调用了一个名为SendMessageView.xaml.cs的文件,这是不正确的。
帮助我正确使用MVVM模式。

最佳答案

在您的项目中添加System.Windows.Interactivity.dll,并在xaml的顶部引用它(xmlns:i =“...”)

然后,您可以执行以下操作:

<ListBox.ItemTemplate>
   <DataTemplate>
      <StackPanel>
         <CheckBox Content="{Binding Path=Item.Name}"
                IsChecked="{Binding RelativeSource={RelativeSource FindAncestor,
                            AncestorType={x:Type ListBoxItem}},
                            Path=IsSelected,Mode=TwoWay}">
             <i:Interaction.Triggers>
                <i:EventTrigger EventName="Checked">
                    <i:InvokeCommandAction Command="{Binding DataContext.OnCheckedCommand, ElementName=myCtrl}" />
                </i:EventTrigger>
             </i:Interaction.Triggers>
         </CheckBox>
      </StackPanel>
   </DataTemplate>
</ListBox.ItemTemplate>

并在ViewModel中使用名为OnCheckedCommand的命令来处理它。

10-06 01:09