Reputation: 217
I am trying to get the currently selected item of a datagrid that I have bound to a CollectionViewSource. However, it appears as if the SelectedItem property is not correctly binding to the property I have set in my ViewModel.
<Grid DataContext="{Binding CollectionView}">
<DataGrid ItemsSource="{Binding}" Margin="0,30,0,0" SelectedItem="{Binding SelectedRow}" />
</Grid>
When running the project, I see this error message in the output box of VS2010.
System.Windows.Data Error: 40 : BindingExpression path error: 'SelectedRow' property not found on 'object' ''BindingListCollectionView' (HashCode=56718381)'. BindingExpression:Path=SelectedRow; DataItem='BindingListCollectionView' (HashCode=56718381); target element is 'DataGrid' (Name=''); target property is 'SelectedItem' (type 'Object')
I understand that the SelectedItem property of the datagrid is trying to bind to the CollectionViewSource, but I am not quite sure how to tell the SelectedItem to bind to the SelectedRow property of my ViewModel. Any help would be appreciated. Also, if you need any more information on my setup, please feel free to ask.
Here is the property in my ViewModel, just in case it is needed:
public DataRow SelectedRow
{
get
{
return _selectedRow;
}
set
{
_selectedRow = value;
OnPropertyChanged("SelectedRow");
}
}
Upvotes: 0
Views: 1398
Reputation: 217
I did some more digging, and was able to come up with a solution. Essentially, I needed to tell the SelectedItem property to look back at the DataContext of the MainWindow.
I changed the XAML to:
<Grid DataContext="{Binding CollectionView}">
<DataGrid ItemsSource="{Binding}" Margin="0,30,0,0" SelectedItem="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}}, Path=DataContext.SelectedRow}">
</DataGrid>
</Grid>
and then change the property within my ViewModel to a DataRowView instead of DataRow
public DataRowView SelectedRow
{
get
{
return _selectedRow;
}
set
{
_selectedRow = value;
OnPropertyChanged("SelectedRow");
}
}
Thanks everyone!
Upvotes: 1
Reputation: 17083
SelectedRow
is not a property of CollectionView
. I assume both are properties of your ViewModel:
<Grid DataContext="{Binding}">
<DataGrid ItemsSource="{Binding CollectionView}"
SelectedItem="{Binding SelectedRow}" />
</Grid>
Upvotes: 0
Reputation: 23157
You have SelectedItem
in your binding, and the name of your property is SelectedRow
- make sure these are the same.
Upvotes: 0
Reputation: 26078
Change DataRow to whatever the actual type of object you are binding too is called.
public **Object each row represents in view model** SelectedRow
{
get
{
return _selectedRow;
}
set
{
_selectedRow = value;
OnPropertyChanged("SelectedRow");
}
}
Upvotes: 1