WPF:将 DataGrid 绑定到 List<String> [英] WPF: Bind DataGrid to List&lt;String&gt;

查看:72
本文介绍了WPF:将 DataGrid 绑定到 List<String>的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有趣的是,有时简单的事情会在背后咬我.

Funny, how sometimes the simple things bite me in the behind.

我可以使用像这样的 DataGridTextColumn 将 DataGrid 很好地绑定到某个任意类的集合:

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 绑定到一个简单的 String 集合.因此,由于没有要绑定到的属性名称"或类似的内容,我该如何编写绑定:

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 没有属性值"或类似的东西.如果我只写 {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?

推荐答案

您可以使用以下 Binding 使其运行:

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.

所以您的想法是正确的,您需要将这些字符串包装在对象中,使用 Binding 的 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 绑定到 List<String>的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆