I have a button in a DataGrid. I need to bind the CommandParameter of this button to the DataItem so that the Predicate of its command will receive information on which piece of data is connected to the button of a given row.
I am using MVVM. Thus far, all objects have been bound rather than using explicit naming or event handlers. The button is being used in the data filtering process. The command works because the ICollectionView object in my ViewModel gets the correct CurrentItem when a button is clicked. Unfortunately, the Predicate needs to operate regardless of which row is selected.
My view looks like this:
<DataGrid Margin="5" ItemsSource="{Binding GridSource}" AutoGenerateColumns="False" IsSynchronizedWithCurrentItem="True" >
<DataGrid.Columns>
<DataGridTextColumn Binding="{Binding Time}" Header="Time" CanUserSort="False"></DataGridTextColumn>
<DataGridTextColumn Binding="{Binding Name}" Header="Name" CanUserSort="False"></DataGridTextColumn>
<DataGridTemplateColumn Header="Exclude Data">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<Button Content="Exclude" Command="{Binding DataContext.ExcludeCommand, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type DataGrid}}}"/>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
</DataGrid.Columns>
</DataGrid>
Note that I had to use a RelativeSource on the command binding. I assume my current problem is related to this. I've tried a lot of things including CommandParameter="{Binding}"
and a couple relative formulas, but the argument in the predicate always comes through null. The only exception I've found is when I name a UIElement and use that. For instance: CommandParameter="{Binding ElementName="SomeName"}"
Is there an element and property (Path value) that would (or should) bind the correct DataItem in each row's button?
Thank you!