- <ListBox ItemsSource="{Binding ClassCollection}">
- <ListBox.ItemContainerStyle>
- <Style TargetType="{x:Type ListBoxItem}">
- <Setter Property="Height" Value="30"/>
- <Setter Property="Template">
- <Setter.Value>
- <ControlTemplate TargetType="ListBoxItem">
- <Grid>
- <Border x:Name="ItemBackground"
- Background="{TemplateBinding Background}"
- BorderBrush="{TemplateBinding BorderBrush}"
- BorderThickness="{TemplateBinding BorderThickness}"/>
-
- <CheckBox Content="{Binding Item2.Name}" IsChecked="{Binding Item1,Mode=TwoWay}">
- <i:Interaction.Triggers>
- <i:EventTrigger EventName="Checked">
- <i:InvokeCommandAction Command="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type local:Control_CodeAutoGeneration}}, Path=DataContext.RelayCommand}"
- CommandParameter="ClassSelectionChanged"/>
- </i:EventTrigger>
-
- <i:EventTrigger EventName="Unchecked">
- <i:InvokeCommandAction Command="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type local:Control_CodeAutoGeneration}}, Path=DataContext.RelayCommand}"
- CommandParameter="ClassSelectionChanged"/>
- </i:EventTrigger>
- </i:Interaction.Triggers>
- </CheckBox>
-
- </Grid>
- </ControlTemplate>
- </Setter.Value>
- </Setter>
- </Style>
- </ListBox.ItemContainerStyle>
- <i:Interaction.Triggers>
- <i:EventTrigger EventName="SelectionChanged">
- <i:InvokeCommandAction Command="{Binding RelayCommand}" CommandParameter="ClassSelectionChanged"/>
- </i:EventTrigger>
- </i:Interaction.Triggers>
- </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的绑定属性或命令
总结:WPF中模板需要绑定父级别的ViewModel该如何处理
原文:https://www.cnblogs.com/lonelyxmas/p/12073363.html