C# 是否从ItemsControl中运行命令?

C# 是否从ItemsControl中运行命令?,c#,wpf,xaml,mvvm,mvvm-light,C#,Wpf,Xaml,Mvvm,Mvvm Light,我有一个itemsControl,它是从ObservableCollection填充的 <ItemsControl ItemsSource="{Binding AvailableSessions}" Margin="490,181,10.111,39.111"> <ItemsControl.ItemTemplate> <DataTemplate> <Border BorderBrush="Black" B

我有一个itemsControl,它是从ObservableCollection填充的

<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内部指定绑定到父网格中的绑定?

问题是ItemsControl的ItemsSource已设置,因此绑定就是从该绑定派生的。只需使用如下的相对源:

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

将包含您想要访问的数据上下文的元素放在案例网格中以代替窗口。

这是有道理的,但是我仍然收到一个设计错误,说无法解析App.Views.MainChatView中的MainChatViewModel。当我运行项目时,单击按钮不会发生任何事情