WPF MVVM Button Control Binding in DataTemplate

前端 未结 3 1748
难免孤独
难免孤独 2021-01-14 09:34

I\'ve seen other questions that deal with this, but never any explicit code describing the fix. I can\'t get a button inside of my ItemTemplate to bind to ANY command anywhe

3条回答
  •  盖世英雄少女心
    2021-01-14 10:01

    The DataContext for the Button inside your ItemTemplate is a PrinterViewModel object (which has the PauseCommand). However, you're trying to bind the PausePrinterCommand to it, which is a property of the MainWindowViewModel.

    In order to make this work (i.e. execute the MainViewModel.PausePrinterCommand using a Button in your ItemTemplate), you'll have to somehow get the MainViewModel first.

    One way to do this is to use a RelativeSource for your binding, find the Window, and use DataContext.PausePrinterCommand as the Binding path. Like this:

提交回复
热议问题