Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
832 views
in Technique[技术] by (71.8m points)

binding - WPF: Bind DataGrid to List<String>

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

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}"/>

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

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; }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...