Kris Harper
Kris Harper

Reputation: 5872

Adding a WPF namespace causes VSTO compile error

I'm getting a weird error in my VSTO project wherein a XAML file is causing a build error in unrelated code.

Here is what I did

  1. Create a new Excel 2010 Add-in project (here named TestAddIn)

  2. Modify ThisAddIn_Startup to read

    private void ThisAddIn_Startup(object sender, System.EventArgs e)
    {
        Worksheet w = Globals.ThisAddIn.Application.Workbooks[1].Sheets[1];
        w.Rows[1].Font.Bold = true;
    }
    
  3. Build project. The build should succeed.

  4. Add a WPF User Control as a New Item to the project. You'll also need to add System.Xaml as a project reference.

  5. Build project again. The build should succeed.

  6. Modify UserControl1.xaml to read

    <UserControl x:Class="TestAddIn.UserControl1"
                 xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                 xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                 xmlns:Test="clr-namespace:TestAddIn" <!-- Add this line -->
                 >
        <Grid>
    
        </Grid>
    </UserControl>
    
  7. Build project. The build fails with error message

    'object' does not contain a definition for 'Font' and no extension method 'Font' accepting a first argument of type 'object' could be found (are you missing a using directive or an assembly reference?)

Removing or adding the namespace line in UserControl1.xaml will cause the build to succeed or fail.

I'm really confused by this because the WPF file has no direct relation to the add-in file. I guess there must be a linking issue?

I realize I can fix this by just doing explicit casts (((Range)w.Rows[1]).Font.Bold = true). But I don't really want to do this all over the place.

How can I fix this so that I can have a WPF file in my VSTO project?

Upvotes: 5

Views: 955

Answers (3)

Thomas
Thomas

Reputation: 31

I found a way to get this working for users of VS2012.

  1. Go to the Solution Explorer -> References folder and select the reference to "Microsoft.Office.Interop.Excel".
  2. Within its properties, set "Embed Interop Types" to False and compile. The errors should still appear. Now set it back to True again and compile. Voilà!

This bug has been fixed in VS2013 (Update 3).

Upvotes: 3

Jeremy
Jeremy

Reputation: 1973

I also ran into this problem and have no idea what the root cause is.

However, I am able to add namespaces to my XAML files if the namespace is defined in a different assembly than the VSTO one.

So this fails with those strange casting errors every time:

xmlns:helper="clr-namespace:MyVstoProject.Utility"

But this works fine:

xmlns:helper="clr-namespace:ReferencedProject.Utility;assembly=SomeNonVstoAssembly"

Upvotes: 1

XAMeLi
XAMeLi

Reputation: 6289

Try adding ;assembly= at the end of the xmlns declaration. Like so:

xmlns:Test="clr-namespace:TestAddIn;assembly="

Upvotes: 1

Related Questions