Data binding access in xaml vs in code behind - Linq to XML?

一曲冷凌霜 提交于 2019-12-11 07:59:03

问题


I have a listbox that binds to and displays the Name elements from an XML file. When a listbox item is selected, I want to display the Price value associated with this item in a textblock. How do I retrieve the Price programmatically (meaning not in the xaml file but in code behind)? Thanks.

XML file has these nodes:

<Product>
    <Name>Book</Name>
    <Price>7</Price>
</Product>

I use Linq and do the select with an anonymous type. If the easiest way to access the field programmatically is through a named type, please show me how.

Here's how I bind in xaml (using a data template for each listbox item that contains):

 <TextBlock Text = "{Binding Name}" />

Here's the code-behind function where I want to retrieve the Price:

        private void listBox1_SelectionChanged(object sender, SelectionChangedEventArgs e)
    { 
       // how do I get the value of Price of the selected item here?
    }

Please note that I want to access Price in this function, NOT in xaml!


回答1:


First of all you probably don't even need LINQ as you can do a lot of things with XmlDocuments including doing selection via XPath (also in Bindings).

Secondly converting anonymous types to named types is trivial, if you have

select new { Name = ..., Price = ... }

You just need a class with the respective properties

select new Product { Name = ..., Price = ... }
public class Product
{
     public string Name { get; set; }
     public string Price { get; set; } // Datatype is up to you...
}

Thirdly you can make do without named types using dynamic.

private void listBox1_SelectionChanged(object sender, SelectionChangedEventArgs e)
{ 
   var listBox = (ListBox)sender;
   // Named type:
   Product item = (Product)listBox.SelectedItem;
   // Anonymous type:
   dynamic item = listBox.SelectedItem;
   // <Do something with item.Price, may need to cast it when using dynamic>
   // e.g. MessageBox.Show((string)item.Price);
}



回答2:


You should be able to retrieve the selected item from the SelectionChangedEventArgs parameter. i.e.

var item = e.AddedItems.First();



回答3:


Refer to this post - bind textblock to current listbox item in pure xaml, you can get the name both in xaml and code-behind using XmlDataProvider.



来源:https://stackoverflow.com/questions/9125135/data-binding-access-in-xaml-vs-in-code-behind-linq-to-xml

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!