ItemsControl按钮点击命令

14

我需要一些快速的帮助,这是我现在的路障。我在ItemsControl中有一个Button,我需要在按钮单击时执行一些任务。我尝试将Command添加到DataTemplate中的Button,但它不起作用。有人能建议下一步该怎么做吗。

<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中实现了命令的代码,但它没有起作用。请给我建议,让我能够进一步进行。

4个回答

24
您的ItemsControl中每个项的DataContext属性都是绑定到该控件的集合中的项。如果该项包含Command属性,则您的代码应该可以正常工作。
然而,通常情况下并非如此。通常会有一个ViewModel,其中包含了ItemsControlObservableCollection类型的项和要执行的Command。如果您是这种情况,您需要更改绑定的Source,以便在ItemsControl.DataContext中查找命令,而不是在ItemsControl.Item[X]中查找。
<Button Command="{Binding 
    RelativeSource={RelativeSource AncestorType={x:Type ItemsControl}}, 
    Path=DataContext.MyCommand}" />

5
补充Rachel的好回答,如果你想把item作为参数传递,使用CommandParameter="{Binding}"... - isntn
+1 这对我非常有效!实际上,我需要绑定到视图中的 Command 而不是 ViewModel,所以我使用了:{Binding RelativeSource={RelativeSource AncestorType={x:Type UserControl}}, Path=MyCommand} - newfurniturey

0
如果您的ViewModel具有类型为ICommand的属性,则可以将ButtonCommand属性绑定到该属性:

XAML:

<DataTemplate DataType="{x:Type my:FooViewModel}">
   <Button Content="Click!" Command="{Binding Path=DoBarCommand}" />
</DataTemplate>

C#:

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

0

0

猜测一下,CommandDetailsButtonClick 是否在 ViewModel 中定义,并且是你的 UserControl(具有 ListStpRules 属性的那个)的 DataContext

ItemTemplate 中按钮的 DataContext 是来自 ListStpRules 的一个项,如果您的命令不在其中,那么绑定就找不到它。

您可以在调试应用程序时在输出窗口中检查 wpf 的诊断消息。如果无法解析绑定,它会在那里写入。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接