【问题标题】:Running Command from within ItemsControl?从 ItemsControl 中运行命令?
【发布时间】:2013-11-03 02:48:35
【问题描述】:

我有一个从 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 中的绑定指定为父网格中的绑定?

【问题讨论】:

    标签: c# wpf xaml mvvm mvvm-light


    【解决方案1】:

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

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

    将包含您想要访问的数据上下文的元素替换为窗口,在您的情况下为 Grid。

    【讨论】:

    • 这是有道理的,但是我仍然收到一个设计错误,提示“无法解析 App.Views.MainChatView 中的 MainChatViewModel”当我运行项目时,单击按钮没有任何反应
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-01-30
    • 2013-04-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多