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

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

问题描述

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>

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

解决方案

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.

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天全站免登陆