總結:WPF中模板需要繫結父級別的ViewModel該如何處理
阿新 • • 發佈:2019-02-17
<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的繫結屬性或命令