[英]Get Xml Content=“{Binding XPath=…}” in event handler “(sender as Button).Content”
Faced a problem.遇到了问题。 The button context uses XML file tags ( dynamic resource DataContext="{DynamicResource XmlResource}"
).按钮上下文使用 XML 文件标签(动态资源DataContext="{DynamicResource XmlResource}"
)。 Everything is fine, I get Content on the buttons correctly ("Name 1", "Name 2", ...).一切都很好,我在按钮上正确获得了内容(“名称 1”,“名称 2”,...)。 Next, in the mouse event, I want to assign the value of the button content to the variable contentText
and display it on the console.接下来,在鼠标事件中,我想将按钮内容的值赋给变量contentText
并显示在控制台上。 However, I did not receive the expected.然而,我没有收到预期的结果。 I received either System.Xml.XmlElement
or empty string.我收到System.Xml.XmlElement
或空字符串。
// XML
<Root>
<Name1>Name 1</Name1>
<Name2>Name 2</Name2>
...
</Root>
// XAML
<Grid DataContext="{DynamicResource XmlResource}">
<Button MouseEnter="ButtonEnter" Content="{Binding XPath=Root/Name1}" />
<Button MouseEnter="ButtonEnter" Content="{Binding XPath=Root/Name2}" />
...
</Grid>
// C#
private void ButtonEnter(object sender, RoutedEventArgs e)
{
// Version 1
string contentText = (sender as Button).Content.ToString();
Console.WriteLine(contentText); // Output value "System.Xml.XmlElement"
// Version 2
string contentText = (sender as Button).Content as string;
Console.WriteLine(contentText); // Output empty string
// Version 3
string contentText = sender.GetType().GetProperty("Content").GetValue(sender, null).ToString();
Console.WriteLine(contentText); // Output value "System.Xml.XmlElement"
}
How do I attach button contents ("Name 1", "Name 2", ...) to contentText
variable?如何将按钮内容(“名称 1”、“名称 2”、...)附加到contentText
变量? Maybe I can't get the exact value, as a dynamic resource DataContext="{DynamicResource XmlResource}"
?也许我无法获得确切的值,作为动态资源DataContext="{DynamicResource XmlResource}"
? thank感谢
Output value "System.Xml.XmlElement" means that Content is XmlElement. Output 值“System.Xml.XmlElement”表示Content为XmlElement。 Cast Content to concrete type and get properties instead of getting its string representation:将 Content 转换为具体类型并获取属性,而不是获取其字符串表示形式:
var contentElement = (sender as Button).Content as System.Xml.XmlElement;
Console.WriteLine(contentElement.InnerText);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.