ItemsControl按钮单击命令

use*_*239 10 wpf user-controls itemscontrol mvvm wpf-controls

我现在需要一些快速帮助,这对我来说是一个障碍.我有Button,ItemsControl我需要在按钮点击上执行一些任务.我尝试添加CommandButtonI temsControl DataTemplate但它不起作用.任何人都可以建议如何进一步.

<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>
Run Code Online (Sandbox Code Playgroud)

在ViewModel中,我已经为Command实现了代码.它不起作用.请为我提出任何解决方案以便继续进行

Rac*_*hel 17

DataContext你的每一个项目ItemsControl是在收集的项目ItemsControl势必会.如果此项包含Command,您的代码应该可以正常工作.

但是,通常情况并非如此.通常,ViewModel包含l ObservableCollection的项目ItemsContro和要执行的Command.如果是这种情况,您需要更改Source绑定,以便查找命令ItemsControl.DataContext,而不是ItemsControl.Item[X]

<Button Command="{Binding 
    RelativeSource={RelativeSource AncestorType={x:Type ItemsControl}}, 
    Path=DataContext.MyCommand}" />
Run Code Online (Sandbox Code Playgroud)

  • 添加Rachel的好答案,如果你想传递item作为参数,请使用CommandParameter ="{Binding}"... (3认同)

Mat*_*ias 0

如果您的 ViewModel 有 type 的属性,ICommand您可以将 的 属性绑定ButtonCommand该属性:

XAML:

<DataTemplate DataType="{x:Type my:FooViewModel}">
   <Button Content="Click!" Command="{Binding Path=DoBarCommand}" />
</DataTemplate>
Run Code Online (Sandbox Code Playgroud)

C#:

public sealed class FooViewModel
{
  public ICommand DoBarCommand
  {
    get;
    private set;
  }
  //...
  public FooViewModel()
  {
     this.DoBarCommand = new DelegateCommand(this.CanDoBar, this.DoBar);
  }
}
Run Code Online (Sandbox Code Playgroud)