Friday, 27 September 2013

WPF datagrid binding issue: first row bound but doesn't update selected item in two-way fashion

WPF datagrid binding issue: first row bound but doesn't update selected
item in two-way fashion

The Setup
I have a DataGrid that holds a list of custom types ("Previous Documents")
and binds to them. That part works correctly.
I have bound the SelectedItemProperty of the datagrid to a property on my
ViewModel called CurrentlySelectedPreviousDocument
I have the left-click action of the datagrid bound to a command called
OpenPreviousDocumentCommand
The OpenPreviousDocumentCommand runs a method called
OpenSelectedPreviousDocument()
OpenSelectedPreviousDocument() uses the CurrentlySelectedPreviousDocument
property to copy a file to the temporary directory and open it.
The Problem
This code works, but only if you click on the first item in the datagrid.
For every other item in the datagrid, it appears that
CurrentlySelectedPreviousDocument is shown as null, so all of the
properties are null.
The Code
XAML DataGrid bindings:
<DataGrid
x:Name="PreviousDocumentsDataGrid"
ItemsSource="{Binding PreviousDocumentsList}"
SelectedItem="{Binding CurrentlySelectedPreviousDocument,
Mode=OneWayToSource}"
SelectionMode="Single"
SelectionUnit="FullRow"
AutoGenerateColumns="False"
IsReadOnly="True"
HorizontalGridLinesBrush="LightGray"
VerticalGridLinesBrush="LightGray"
BorderBrush="Transparent"
Visibility="{Binding PreviousDocumentsFound, Converter={StaticResource
BoolToVisConverter}}">
<DataGrid.InputBindings>
<MouseBinding Gesture="LeftDoubleClick" Command="{Binding
OpenPreviousDocumentCommand}"/>
</DataGrid.InputBindings>
<DataGrid.Columns>
<DataGridTextColumn Header="Name" Binding="{Binding Name}"/>
<DataGridTextColumn Header="Reference Type" Binding="{Binding
ReferenceType}"/>
<DataGridTextColumn Header="Category ID" Binding="{Binding
Category}"/>
<DataGridTextColumn Header="Description" Binding="{Binding
Description}"/>
<DataGridTextColumn Header="Document Timestamp" Binding="{Binding
Timestamp}"/>
</DataGrid.Columns>
</DataGrid>
The ViewModel definition of CurrentlySelectedPreviousDocument:
public VEDocument CurrentlySelectedPreviousDocument
{
get { return _currentlySelectedPreviousDocument; }
set { _currentlySelectedPreviousDocument = value;
OnPropertyChanged("CurrentlySelectedPreviousDocument");} //TODO: Is
the on propertychanged actually necessary here?
}
Command Definition:
public ICommand OpenPreviousDocumentCommand
{
get
{
return _openPreviousDocumentCommand ??
(new CommandHandler(OpenSelectedPreviousDocument,
_canExecuteCommands));
}
}
Method in the ViewModel to open the document (uses the viewmodel property)
public void OpenSelectedPreviousDocument()
{
var docToOpen = CurrentlySelectedPreviousDocument;
...etc. etc.
}

No comments:

Post a Comment