I have a xaml code like this
<StackPanel x:Name="stackPanel">
<TextBox>Text</TextBox>
<Button>Content</Button>
<Border>
<StackPanel>
<TextBox>Text</TextBox>
</StackPanel>
</Broder>
</StackPanel>
I am reading this conetnt as a string and want to get whole sentence after first line of StackPanel and before end of StackPanel of parent StackPanel. I mean
<TextBox>Text</TextBox>
<Button>Content</Button>
<Border>
<StackPanel>
<TextBox>Text</TextBox>
</StackPanel>
</Broder>
How is this possible ??
CodePudding user response:
Actually, this is just about string parsing or using an XML-Lib, not exactely WPF related although the string parsed is XAML..
Assuming the XAML block ends with an explicit closing tag (</StackPanel>
) and you only pass in the tag in question and not the complete XAML of your file, might roughly get along with this one, though it could be improved in some ways. Especially the lookup for the starting tag is safer when done by a Regex, to avoid mismatches with tags that extend another tag's name, like ListBox
and ListBoxItem
.
But for getting the inner XAML of a StackPanel it should suffice.
const string wholeXAML =
@"<StackPanel x:Name=""stackPanel"">
<TextBox>Text</TextBox>
<Button>Content</Button>
<Border>
<StackPanel>
<TextBox>Text</TextBox>
</StackPanel>
</Border>
</StackPanel>";
var innerXAML = GetInnerXAML(wholeXAML, "StackPanel");
Console.Write($"*{innerXAML}*");
private string GetInnerXAML(string wholeXAML, string tagName) {
var start = $"<{tagName}";
var end = $"</{tagName}>";
var sPos = wholeXAML.IndexOf(start);
var ePos = wholeXAML.LastIndexOf(end);
if (sPos < 0 || ePos < 0) return null;
if (ePos <= sPos) return null;
var innerXAML = wholeXAML.Substring(sPos tagName.Length, ePos - sPos - tagName.Length);
return innerXAML;
}