I’ve spent quite a few hours trying to solve the problem described below:
I’ve got a DataGrid defined in my MVVM WPF application, the stripped down XAML code looks like this:
<DataGrid AutoGenerateColumns="False" Name="dgdSomeDataGrid" SelectedItem="{Binding SelectedSomeItem, Mode=TwoWay}" ItemsSource="{Binding SomeItemCollection}">
<DataGrid.Columns>
<DataGridTextColumn Binding="{Binding Path=Id}" Header="ID" />
<DataGridTextColumn Header="Titel" Binding="{Binding Path=Title}" />
<DataGridTextColumn Header="Status" Binding="{Binding Path=State}" />
</DataGrid.Columns>
</DataGrid>
In my associated ViewModel I’ve got a corresponding property like:
public WorkItemForUi SelectedSomeItem
{
get
{
return SomeObject.SelectedSomeItem;
}
set
{
SomeObject.SelectedSomeItem = value;
OnPropertyChanged( "SelectedSomeItem" );
}
}
In my controller I’ve got the following:
private void MainWindowViewModelPropertyChanged( object sender, PropertyChangedEventArgs e )
{
if ( e.PropertyName == "SelectedSomeItem" )
{
UpdateSelectedSomeItem();
}
}
What I generally want to do is to retrieve the selected item from the DataGrid, get some more information about the item from an external data store (a TFS in this case) and show that extra information in a TextBox.
All of this already works as expected, but the problem is that the MainWindowViewModelPropertyChanged method is called twice, not once.
It may be the case that it is by design for the SelectedItem property being set to happen twice, but I’m not quite sure as a lot of information I found is a bit contradictory (and also sometimes not quite clear whether Windows Forms or WPF are meant).
I’ve seen some suggestions where a SelectionChanged event handler is defined for the DataGrid and an IsSelected property is used, but as far as I know this shouldn’t be necessary due to my data binding.
Update
As part of the MainWindowController there is an Initialize method that references the MainWindowViewModelPropertyChanged handler.
public void Initialize( string tfsProjectCollection )
{
InitializeCommands();
InitializeViewModel();
AddWeakEventListener( m_MainWindowViewModel, MainWindowViewModelPropertyChanged );
}
Any ideas what might be the cause of my problem?
Alright, after spending some more time on this we found out that the problem was in the
ApplicationControllerclass.The constructor called the
Initializemethod in that class, and theRunmethod in the same class also called this method.Within the
Initializemethod there was a call to the main window’s view model `Initialize´ method in which an event listener was added:Removing the call to the
Initializemethod from the constructor of theApplicationControllerclass solved the problem.