WPF:绑定DataGrid中列出&LT;串GT; [英] WPF: Bind DataGrid to List<String>
问题描述
搞怪,怎么有时简单的东西咬我的后面。
Funny, how sometimes the simple things bite me in the behind.
我可以很好地绑定一个DataGrid一些任意类的集合,使用DataGridTextColumn是这样的:
I can bind a DataGrid nicely to a Collection of some arbitrary class, using a DataGridTextColumn like this:
// bound to List<Class>
<DataGridTextColumn Header="Name" Binding="{Binding Name}"/>
现在我想一个DataGrid绑定到字符串的简单集合。所以,既然没有财产名称或者类似的东西绑定到,我怎么写绑定:
Now I want to bind a DataGrid to a simple Collection of String. So since there is no property "Name" or something like that to bind to, how do I write the binding:
// bound to List<String>
<DataGridTextColumn Header="Name" Binding="{Binding ???}"/>
字符串没有财产值或者类似的东西。如果我只是写{}绑定我会最终有一个单向绑定,无法写入更改回收藏。
String has no Property "Value" or something like that. And if I just write {Binding } I'll end up with a one-way-binding, unable to write changes back to the Collection.
关于它的思考,我认为这是不可能绑定到一个集合的,所以我需要我的字符串包装成一个类?结果
或者有没有办法?
Thinking about it, I think it is not possible to bind to a collection, so I do need to wrap my string into a class?
Or is there a way?
推荐答案
您可以把它与运行以下绑定:
You can make it run with the following Binding:
Binding="{Binding Path=.}
但它不会解决你的问题,因为字符串类型的引用是不可变的,这意味着你不能改变字符串的参考已经绑定到用户界面。
But it wont solve your problem, because strings are reference typed that are immutable, meaning you cannot change the string reference you have bound to your user interface.
所以,你的想法是正确的,你需要在对象换这些字符串,使用绑定的path属性和饲料这些对象中的DataGrid。
So your thoughts are correct, you will need to wrap these strings in objects, use the path property of Binding and feed these objects to your DataGrid.
public class StringWrapper
{
public string Value { get; set; }
}
这篇关于WPF:绑定DataGrid中列出&LT;串GT;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!