I'm working on a C# application that extracts and converts embedded BAML resources from a .DLL into XAML using ILSpy and Mono.Cecil. The current implementation successfully retrieves and prints the XAML content.
Now, I need to modify my code to check if the extracted XAML contains any Binding expressions, such as:
Text="{Binding PropertyName}"
The goal is to return true if any Binding expression is found in the XAML content, otherwise false.
Current Code Here is my current implementation for extracting and converting BAML to XAML:
public static string ConvertBamlToXaml(Stream bamlStream)
{
using (bamlStream)
{
if (!isValidBaml(bamlStream))
{
throw new Exception("Il file estratto dalla DLL non è un Baml valido!");
}
BamlDocument bamlDoc = BamlReader.ReadDocument(bamlStream, CancellationToken.None);
StringBuilder xamlBuilder = new StringBuilder();
Stack<string> elementStack = new Stack<string>();
xamlBuilder.Append("<Root>");
foreach (BamlRecord record in bamlDoc)
{
switch (record.Type)
{
case BamlRecordType.DocumentStart:
xamlBuilder.Append("-- XAML document start --");
break;
case BamlRecordType.ElementStart:
if(record is ElementStartRecord elementStart)
{
string elementName = $"Element_{elementStart.TypeId}";
xamlBuilder.AppendLine($"{new string(' ', elementStack.Count * 2)}{elementName}");
elementStack.Push(elementName);
}
break;
case BamlRecordType.Property:
if(record is PropertyRecord property)
{
xamlBuilder.AppendLine($"{new string(' ',elementStack.Count*2+2)}{property.AttributeId}=\"{property.Value}\"");
}
break;
case BamlRecordType.Text:
if(record is TextRecord textRecord)
{
xamlBuilder.AppendLine($"{new string(' ', elementStack.Count * 2 + 2)}{textRecord.Value}");
}
break;
case BamlRecordType.ElementEnd:
if(elementStack.Count>0)
{
string elementName = elementStack.Pop();
xamlBuilder.AppendLine($"{new string(' ', elementStack.Count * 2)}</{elementName}>");
}
break;
case BamlRecordType.DocumentEnd:
xamlBuilder.AppendLine("!---XAML document end ----");
break;
}
}
xamlBuilder.AppendLine("</Root>");
return xamlBuilder.ToString();
}
}
I am not sure if this is the best approach to detect {Binding PropertyName} in the converted XAML.
Should I modify my ConvertBamlToXaml method to perform a proper XAML parsing instead of searching for "Binding" in the raw BAML records?
Is there a more efficient way to extract only the Binding properties from the BAML?
Any guidance or examples on improving this would be greatly appreciated!
Thanks in advance!