简体   繁体   中英

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}" ). Everything is fine, I get Content on the buttons correctly ("Name 1", "Name 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. However, I did not receive the expected. I received either System.Xml.XmlElement or empty string.

// 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? Maybe I can't get the exact value, as a dynamic resource DataContext="{DynamicResource XmlResource}" ? thank

Output value "System.Xml.XmlElement" means that Content is XmlElement. Cast Content to concrete type and get properties instead of getting its string representation:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM