internal static bool TryUpdateUsage(string fileName, IPropertySymbol resource, string newName, out XamlFile result) { var xaml = XamlFile.Create(fileName); var pattern = $"xmlns:(?<alias>\\w+)=\"clr-namespace:{resource.ContainingType.ContainingSymbol}(\"|;)"; if (Regex.Match(xaml.Text, pattern) is Match match && match.Success && match.Groups["alias"].Value is string alias && !string.IsNullOrEmpty(alias)) { var oldProperty = $"{alias}:{resource.ContainingType.Name}.{resource.Name}"; var newProperty = $"{alias}:{resource.ContainingType.Name}.{newName}"; var updated = Replace(xaml.Text, " {0}}}", oldProperty, newProperty); updated = Replace(updated, "({0})", oldProperty, newProperty); updated = Replace(updated, "\"{0}\"", oldProperty, newProperty); if (updated != xaml.Text) { result = new XamlFile(updated, xaml.Encoding); return(true); } } result = default(XamlFile); return(false); }
private static void UpdateXaml(Project project, IPropertySymbol property, string newName) { if (project.MetadataReferences.TryFirst(x => x.Display.EndsWith("System.Xaml.dll"), out _)) { var directory = Path.GetDirectoryName(project.FilePath); var csprojText = File.ReadAllText(project.FilePath); if (Regex.IsMatch(csprojText, "<TargetFrameworks?\b")) { var csproj = XDocument.Parse(csprojText); if (csproj.Root is XElement root) { foreach (var page in root.Descendants().Where(x => x.Name.LocalName == "Page")) { if (page.Attribute("Include") is XAttribute attribute && attribute.Value.EndsWith(".xaml")) { var fileName = Path.Combine(directory, attribute.Value); if (XamlFile.TryUpdateUsage(fileName, property, newName, out var xamlFile)) { File.WriteAllText(fileName, xamlFile.Text, xamlFile.Encoding); } } } } } else { foreach (var fileName in Directory.EnumerateFiles(directory, "*.xaml", SearchOption.AllDirectories)) { if (XamlFile.TryUpdateUsage(fileName, property, newName, out var xamlFile)) { File.WriteAllText(fileName, xamlFile.Text, xamlFile.Encoding); } } } } }