ItemsControl按钮单击命令 [英] ItemsControl button click command

查看:96
本文介绍了ItemsControl按钮单击命令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要一些快速帮助,现在对我来说这是一个路障.我在ItemsControl中有Button,我需要在按钮单击上执行一些任务.我尝试将Command添加到I temsControl DataTemplate中的Button,但是它不起作用.谁能建议进一步进行下去.

I need some quick help which is a road blocker for me now. I have Button in ItemsControl and I need to perform some task on Button click. I tried adding Command to Button in ItemsControl DataTemplate but its not working. Can anyone suggest how to proceed further.

<UserControl.Resources>
    <DataTemplate x:key="mytask">
        <TextBox Grid.Row="5" Grid.Column="2" Text="{Binding Path=PriorNote}" Grid.ColumnSpan="7"  VerticalAlignment="Center" HorizontalAlignment="Left" Margin="0,5" Width="505" Foreground="Black"/>
        <StatusBarItem Grid.Row="2" Grid.Column="8" Margin="8,7,7,8" Grid.RowSpan="2">
        <Button x:Name="DetailsButton" Command="{Binding CommandDetailsButtonClick}">
    </DataTemplate>
</UserControl.Resources>

<Grid>
    <ItemsControl Grid.Row="1" 
                  ItemsSource="{Binding ListStpRules}" 
                  ItemTemplate="{StaticResource myTaskTemplate}" Background="Black"
                  AlternationCount="2" >
    </ItemsControl>
</Grid>

在ViewModel中,我已经实现了Command的代码.而且它不起作用.请为我提出进一步解决方案的建议

and in ViewModel I have implemented code for Command. And its not working. Please suggest any solution for me to proceed further

推荐答案

ItemsControl中每个项目的DataContextItemsControl绑定到的集合中的项目.如果该项目包含Command,则您的代码应该可以正常工作.

The DataContext of each item in your ItemsControl is the item in the collection the ItemsControl is bound to. If this item contains the Command, your code should work fine.

但是,通常情况并非如此.通常,存在一个ViewModel,其中包含ItemsContro l的项的ObservableCollection和要执行的命令.如果是这种情况,则需要更改绑定的Source,以便它在ItemsControl.DataContext中而不是ItemsControl.Item[X]

However, this is not usually the case. Typically there is a ViewModel containing an ObservableCollection of items for the ItemsControl, and the Command to execute. If this is your case, you'll need to change the Source of your binding so it looks for the command in ItemsControl.DataContext, not ItemsControl.Item[X]

<Button Command="{Binding 
    RelativeSource={RelativeSource AncestorType={x:Type ItemsControl}}, 
    Path=DataContext.MyCommand}" />

这篇关于ItemsControl按钮单击命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆