-1

我有一个从 ObservableCollection 填充的 itemsControl。

<ItemsControl ItemsSource="{Binding AvailableSessions}" Margin="490,181,10.111,39.111">
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <Border  BorderBrush="Black" Background="Gainsboro" BorderThickness="1" Margin="2">
                <!-- This is the Inner Grid for each element, which is represented in 
                 Brown color in your picture -->
                <Grid HorizontalAlignment="Left" Height="134"  VerticalAlignment="Top" 
                  Width="263" Background="#FFECECEC">
                    <Button HorizontalAlignment="Left" Margin="10,10,0,0" 
                      VerticalAlignment="Top" Width="243" Height="42" Command="{Binding 
                      OpenSessionCommand, Mode=OneWay}">
                    <TextBlock TextWrapping="Wrap"><Run Text="{Binding SessionName}"/>                                                 
                       <LineBreak/><Run Text="{Binding Genre}"/><Run Text=" - "/>
                       <Run Text="{Binding Tempo}"/><Run Text=" BPM"/><LineBreak/>
                    </TextBlock>
                    </Button>
                    <Label Content="{Binding SessionName}" HorizontalAlignment="Left" 
                      Margin="10,53,0,0" VerticalAlignment="Top" Width="243" 
                      Height="26"/>
                    <Label Content="Drummmman - Electronic Drums"                         
                     HorizontalAlignment="Left" Margin="10,71,0,0" 
                      VerticalAlignment="Top" Width="243" Height="25"/>
                </Grid>
            </Border>
        </DataTemplate>
    </ItemsControl.ItemTemplate>

当我单击 OpenSessionCommand 按钮时,没有任何反应。当我将它绑定到 ItemsControl 之外时,这可以正常工作。我是否必须将此命令添加为 observablecollection 中的属性?或者有没有办法在 ItemsSource 中指定绑定到父网格中的绑定?

4

1 回答 1

2

问题是 ItemsControl 的 ItemsSource 已设置,因此这是您的绑定的来源。只需像这样使用相对源:

<Button Command="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}}, Path=DataContext.OpenSessionCommand}"/>

代替 window 放置包含您要访问的数据上下文的元素,在您的情况下为 Grid。

于 2013-11-03T03:00:06.580 回答