Andrew Simpson Andrew Simpson - 3 months ago 18
C# Question

how to set binding path expliclitly

I have a wpf desktop app.

I am using the datagrid and I populate my grid using a view-model architecture.

I also have a button for each row.

I have bound a button (tried) to a command object.

So.

This my MVVM:

public class Navigation
{
private ICommand _ViewJobAction;
public ICommand ViewJobAction
{
get
{
try
{
if (_ViewJobAction == null)
{
_ViewJobAction = new MyCommand(
param => ViewJob()
);
}
return _ViewJobAction;
}
catch (Exception ex)
{
//handle error
}
return null;
}
}
private void ViewJob()
{
//do some stuff
}

private Customers _CustomerRecords;
public Customers CustomerRecords
{
get
{
return _CustomerRecords;
}
set
{
_CustomerRecords = value; RaisePropertyChanged("CustomerRecords");
}
}
}

public class Customers
{
//get data
}


in my view:

<DataGrid "{Binding Navigation.CustomerRecords.Records}">
//defined columns
<DataGridTemplateColumn.CellTemplate>
<DataGridTemplateColumn>
<Button Command="{Binding Navigation.ViewJobAction ,UpdateSourceTrigger=Explicit}" Content="View Job">
</Button>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>


This does not invoke my Command in my VM.

In the output window I get this:

System.Windows.Data Error: 40 : BindingExpression path error: 'Navigation' property not found on 'object' ''CustomerRecord' (HashCode=26023080)'. BindingExpression:Path=Navigation.ViewJobAction; DataItem='CustomerRecord' (HashCode=26023080); target element is 'Button' (target property is 'Command' (type 'ICommand')


Now I think i understand this error but I do not know how to fix it apart from moving the ViewAction Code to the customer Class which i do not want to do.

My last attempt to get this working was putting the explicit' option in.

help?

Answer

You can set the RelativeSource of the binding to point to the DataGrid, and then bind to a property of its DataContext:

<Button Command="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type DataGrid}}, Path=DataContext.ViewJobAction, UpdateSourceTrigger=Explicit}"
        Content="View Job" />
Comments