Today we will write code that reads the contents (values & formulas) of the two selected worksheets, generates a list of their differences, and feeds it to the view that displays the comparison. The code isn’t particularly complicated, and uses mostly ideas which have been seen in the previous posts, so rather than break this into multiple small posts, I chose to bite the bullet and get done with a large chunk, all at once. I hope you survive it and bear with me – promise, we are almost there!
You can find the complete list of episodes, and a link to the source code of theExcel VSTO add-in tutorial here.
Extracting the comparison from the comparison ViewModel
In the previous installment, I created a stub to provide a “canned” list of differences to the ComparisonViewModel, so that we would have something to display. It’s time to replace that stub, and generate a real comparison between 2 worksheets. We could add the required code inside the existing classes; however, we will likely have a good amount of logic, so to avoid clutter, and to keep our design tight, we will extract that responsibility into its own class, the WorksheetsComparer.
First, let’s create a stub for the class, in the Comparison folder; its key method will be FindDifferences, and we will temporarily move the “fake” comparison that was in the ComparisonViewModel into that method:
public class WorksheetsComparer
{
public static List<Difference> FindDifferences(Excel.Worksheet firstSheet, Excel.Worksheet secondSheet)
{
// Temporary code
var difference1 = new Difference() { Row = 3, Column = 3 };
var difference2 = new Difference() { Row = 3, Column = 5 };
var difference3 = new Difference() { Row = 5, Column = 8 };
var differences = new List<Difference>();
differences.Add(difference1);
differences.Add(difference2);
differences.Add(difference3);
return differences;
}
}
Now we need to hook it up to the add-in. We will add a button to the AnakinView, which, when clicked, will call WorksheetsComparer.FindDifferences, and pass the result to the ComparisonViewModel. Let’s first plug a button in the AnakinView, and bind it to a Command on the ViewModel, GenerateComparison:
<StackPanel Margin="5">
<Comparison:ComparisonView x:Name="ComparisonView" />
<Button Command="{Binding GenerateComparison}"
Content="Compare" Width="75" Height="25" Margin="5"/>
Following the same approach as in the previous post, we implement the command in the View Model (only added code is displayed):
public class AnakinViewModel
{
private ICommand generateComparison;
public ICommand GenerateComparison
{
get
{
if (this.generateComparison == null)
{
this.generateComparison = new RelayCommand(GenerateComparisonExecute);
}
return this.generateComparison;
}
}
private void GenerateComparisonExecute(object target)
{
var differences = WorksheetsComparer.FindDifferences(null, null);
this.comparisonViewModel.SetDifferences(differences);
}
}
More...