我使用的是ItemsControl,其中包含对象列表...在ItemContainerTemplate内,我还有另一个DataTemplate。在那个DataTemplate里面,我不能再绑定(bind)到ItemsControl.ItemSource了。

由于我对通过Find AncestorRelativeSource等进行的绑定(bind)不是很好。我尝试了所有操作,甚至都不知道如何正确使用它们...

<ItemsControl ItemsSource="{Binding NoteList}">
  <ItemsControl.ItemTemplate>
    <ItemContainerTemplate>
      <GroupBox Header="{Binding Title}"
                Name="MyNoteList"
                Style="{DynamicResource MaterialDesignCardGroupBox}"
                Margin="16">
        <GroupBox.HeaderTemplate>
          <DataTemplate>
            <DockPanel>
              <TextBlock Margin="8,0,0,0"
                         VerticalAlignment="Center"
                         Style="{StaticResource MaterialDesignSubheadingTextBlock}"
                         Text="{Binding}" />
              <Button Padding="5"
                      Command="{Binding DataContext.DeleteCommand, RelativeSource={RelativeSource AncestorType=UserControl}}"
                      CommandParameter="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ItemsControl}}, Path=DataContext.NoteId}"
                      HorizontalAlignment="Right"
                      Background="Transparent"
                      BorderBrush="Transparent">
                <materialDesign:PackIcon Kind="Delete"
                                         Height="25"
                                         Width="25"
                                         VerticalAlignment="Center" />
              </Button>
            </DockPanel>
          </DataTemplate>
        </GroupBox.HeaderTemplate>
      </GroupBox>
    </ItemContainerTemplate>
  </ItemsControl.ItemTemplate>
</ItemsControl>

我想提到的是,我想绑定(bind)到NoteList中名称为NoteIdCommandParameter中的对象。但是我一直从中得到“空”。我的ViewModel内部的绑定(bind)肯定是正确的。所以我只需要知道如何从我的NoteId访问NoteList属性

最佳答案

我实际上已经解决了问题! xD!我只需要绑定(bind)到ItemContainerTemplate内部的Element,就我而言,就是绑定(bind)到GroupBox(在上面的代码片段中看到)。

CommandParameter="{Binding DataContext.NoteId, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type GroupBox}}}"

关于c# - 如何正确绑定(bind)到数据模板中的项目源,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/57018395/

10-11 14:18
查看更多