原文:总结:WPF中模板需要绑定父级别的ViewModel该如何处理


  1. <ListBox ItemsSource="{Binding ClassCollection}">
  2. <ListBox.ItemContainerStyle>
  3. <Style TargetType="{x:Type ListBoxItem}">
  4. <Setter Property="Height" Value="30"/>
  5. <Setter Property="Template">
  6. <Setter.Value>
  7. <ControlTemplate TargetType="ListBoxItem">
  8. <Grid>
  9. <Border x:Name="ItemBackground"
  10. Background="{TemplateBinding Background}"
  11. BorderBrush="{TemplateBinding BorderBrush}"
  12. BorderThickness="{TemplateBinding BorderThickness}"/>
  13. <CheckBox Content="{Binding Item2.Name}" IsChecked="{Binding Item1,Mode=TwoWay}">
  14. <i:Interaction.Triggers>
  15. <i:EventTrigger EventName="Checked">
  16. <i:InvokeCommandAction Command="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type local:Control_CodeAutoGeneration}}, Path=DataContext.RelayCommand}"
  17. CommandParameter="ClassSelectionChanged"/>
  18. </i:EventTrigger>
  19. <i:EventTrigger EventName="Unchecked">
  20. <i:InvokeCommandAction Command="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type local:Control_CodeAutoGeneration}}, Path=DataContext.RelayCommand}"
  21. CommandParameter="ClassSelectionChanged"/>
  22. </i:EventTrigger>
  23. </i:Interaction.Triggers>
  24. </CheckBox>
  25. </Grid>
  26. </ControlTemplate>
  27. </Setter.Value>
  28. </Setter>
  29. </Style>
  30. </ListBox.ItemContainerStyle>
  31. <i:Interaction.Triggers>
  32. <i:EventTrigger EventName="SelectionChanged">
  33. <i:InvokeCommandAction Command="{Binding RelayCommand}" CommandParameter="ClassSelectionChanged"/>
  34. </i:EventTrigger>
  35. </i:Interaction.Triggers>
  36. </ListBox>

其中、需要在代码

<i:InvokeCommandAction Command="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type local:Control_CodeAutoGeneration}}, Path=DataContext.RelayCommand}"   CommandParameter="ClassSelectionChanged"/>

处绑定的父级别,Control_CodeAutoGeneration是我自定义的控件的ViewModel里面的RelayCommand命令,通过如上传递可以调用到父级别的ViewModel的绑定属性或命令

05-07 15:08