数据绑定访问在xaml vs的代码背后 - Linq到XML? [英] Data binding access in xaml vs in code behind - Linq to XML?
问题描述
XML文件具有以下节点:
< Product> ;
< Name> Book< / Name>
< Price> 7< / Price>
< / Product>
我使用Linq并执行选择
匿名类型。如果以编程方式访问现场的最简单的方法是通过命名类型,请告诉我如何。
以下是我在xaml中绑定的方式(使用每个列表框项目的数据模板包含):
< TextBlock Text ={Binding Name}/>
这是代码隐藏功能,我想检索价格:
private void listBox1_SelectionChanged(object sender,SelectionChangedEventArgs e)
{
//如何获取所选项目的价格值这里?
}
请注意,我想访问此功能的价格,在xaml!
首先你可能不需要LINQ,因为你可以做很多包含 其次将匿名类型转换为命名类型是微不足道的,如果您有 XmlDocuments
的内容包括通过XPath进行选择(
select new {Name = ...,Price = ...}
您只需要一个具有相应属性的课程
选择新产品{Name = ...,Price = ...}
public class Product
{
public string Name {get;组; }
public string Price {get;组; } //数据类型取决于你...
}
第三,你可以做没有命名类型,使用 动态
。
private void listBox1_SelectionChanged(object sender,SelectionChangedEventArgs e)
{
var listBox =(ListBox)sender;
//命名类型:
产品item =(Product)listBox.SelectedItem;
//匿名类型:
动态项= listBox.SelectedItem;
//<使用item.Price执行某些操作,可能需要在使用动态>
//例如MessageBox.Show((string)item.Price);
}
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!
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);
}
这篇关于数据绑定访问在xaml vs的代码背后 - Linq到XML?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!