binding to observable collection silverlight 4, grid
Can I bind a simple 'grid' to an observable collection? So i have a grid with just one column and several rows. The rows get populated at runtime with some hyperlinks which 开发者_StackOverflow中文版can get deleted/added etc. I don't want to write functions to add/remove them from the grid everytime and would prefer to use an observable collection and let the grid update itself. Can a simple grid do that ? i tried but it didn't even compile.
Thanks
[EDIT] Solved. The marked answer is correct [/EDIT]
Other answers cover various bases but your specific requirement is filled by the ItemsControl
. You would probably want to contain it in ScrollViewer
just in case where you have more links than can be seen at one time. You would have markup something like this:-
<ScrollViewer>
<ItemsControl ItemsSource="{Binding MyObsCollectionOfUrlInfo">
<ItemsControl.ItemTemplate>
<DataTemplate>
<HyperLinkButton NavigateUri={Binding Uri} Content={Binding Title} />
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</ScrollViewer>
Your observable collection would contain a list of objects of a type like:-
public class UrlInfo
{
public Uri Uri {get; set; }
public string Title {get; set; }
}
Silverlight does not support this. You have two options, either use a DataGrid
or use the following code that allows you to use a Grid
within an ItemsControl
which will achieve what you are after.
http://www.scottlogic.co.uk/blog/colin/2010/11/using-a-grid-as-the-panel-for-an-itemscontrol/
@ColinE is correct, you can't bind to a Grid
, but you can bind an ObservableCollection
to a DataGrid
or an ItemsControl
.
精彩评论