ItemsControl button click command

…衆ロ難τιáo~ 提交于 2019-12-03 06:17:55
Rachel

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}" />
Matthias

If your ViewModel has a property of type ICommand you can bind the Button's Command property to that:

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);
  }
}
Sreedharlal B Naick

Read this:

http://msdn.microsoft.com/en-us/magazine/dd419663.aspx

Implement a class similar to RelayCommand in the above article. Would make your further MVVM coding easier. :-)

Nikolay

Just a guess. Is CommandDetailsButtonClick defined in a ViewModel, which is DataContext of your UserControl (the one with ListStpRules property)?

DataContext of button in ItemTemplate is an item from ListStpRules, and if you command is not there then binding won't find it.

You can check diagnostic messages from wpf in Output window while debugging your application. It writes there if it can not resolve binding.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!