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
The button in the datatemplate should bind to command PauseCommand since it's datacontext is PrinterViewModel and not MainWindowViewModel. If you look in the debug output VS will clearly tell you that.
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:
<Button Grid.Column="1" Content="Pause"
Command="{Binding RelativeSource={RelativeSource Window},
Path=DataContext.PausePrinterCommand}" />
use element binding
<Window x:Class="RET.CMS.Printing.App.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:RET.CMS.Printing.App.ViewModel"
Height="350" Width="525"
x:Name="rootWindow"
WindowStartupLocation="CenterScreen"
Title="{Binding Path=DisplayName}" >
.
.
.
<Button Grid.Column="1" Content="Pause" Command="{Binding ElementName=rootWindow, Path=DataContext.PausePrinterCommand}"></Button>