MBi
MBi

Reputation: 61

Unable to retreive XAML members of Control via Roslyn Compilation

Given an INamedTypeSymbol of a WPF Window, I can't seem to obtain a ISymbol for the members that are defined in XAML (and are then compiled as part of the auto-generated .g.cs file).

To reproduce the problem I'm having,

  1. Create a new blank WPF application in Visual Studio
  2. Add <TextBlock Name="tb1"/> to MainWindow.xaml
  3. Put the following code in the MainWindow.xaml.cs method and invoke it:
private async void Compile()
{
    var workspace = MSBuildWorkspace.Create();
    workspace.LoadMetadataForReferencedProjects = true;
    var solution = await workspace.OpenSolutionAsync(@"..\..\WpfApp1.Sln");            
    var project = solution.Projects.Single();
    // this doesn't help
    project = project.WithCompilationOptions(project.CompilationOptions.WithMetadataImportOptions(MetadataImportOptions.All)); 
    var comp = await project.GetCompilationAsync();          
    INamedTypeSymbol mainWindow = comp.GetTypeByMetadataName(GetType().FullName);
    var members = mainWindow.GetMembers();
    Debug.Assert(members.Any(m => m.Name == nameof(tb1)));
}

As you can see, the assertion fails, and I cannot seem to find the ISymbol that represents the "tb1" member field.

members.Length  == 2;        // true
members[0].Name == ".ctor"   // true
members[1].Name == "Compile" // true

How can I get tb1 without resorting to setting x:FieldModifier="public" on the TextBlock?

Upvotes: 1

Views: 104

Answers (0)

Related Questions