在事件处理程序"(sender as Button).Content "中获取Xml Content="{Binding XPath=...}"

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了在事件处理程序"(sender as Button).Content "中获取Xml Content="{Binding XPath=...}"相关的知识,希望对你有一定的参考价值。

面临一个问题。按钮上下文使用XML文件标签(动态 资源 DataContext="{DynamicResource XmlResource}"). 一切都很好,我得到了按钮上正确的内容("名称1","名称2",...)。接下来,在鼠标事件中,我想把按钮内容的值分配给变量 contentText 并将其显示在控制台上。然而,我没有收到预期的。我收到的是 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"
}

如何将按钮内容("名称1"、"名称2"...)附加到 contentText 变量?也许我无法得到准确的值,作为一个动态资源的 DataContext="{DynamicResource XmlResource}"谢谢

答案

输出值 "System.Xml.XmlElement "意味着Content是XmlElement。将Content转为具体类型并获取属性,而不是获取其字符串表示。

var contentElement = (sender as Button).Content as System.Xml.XmlElement;
Console.WriteLine(contentElement.InnerText);

以上是关于在事件处理程序"(sender as Button).Content "中获取Xml Content="{Binding XPath=...}"的主要内容,如果未能解决你的问题,请参考以下文章