开发者

How to set itemsource for DataGrid to some array from ViewModel

Here is my try :

<DataGrid 
    Grid.Row="0" 
    AutoGenerateColumns="True"  
    ItemsSource="{Binding Path = Workers}" 
    Grid.ColumnSpan="1" 
    Name="DataGrid">
</DataGrid>
private Worker[] workers;
public Worker[] Workers
{
    get
    {
        if (IsInDesignMode) return null;
        return serviceAgent.ParseFile("dataWorkers.xml").ToArray() ;
    }
    set
    {
        workers = value;
        NotifyPropertyChanged(m => m.Workers);
    }
}

But my DataGrid still being empty. What am I doing wron开发者_如何学Pythong ?


Works as advertised for me. The following results in an auto-populated editable sortable grid for me. So first begin by faking the workers array as shown below and see if it works. If yes, investigate your ParseFile method. If not, look if you have data binding setup correctly - work to get the fake array into the view first.

  • XAML

=

<StackPanel>
        <DataGrid  AutoGenerateColumns="True"  
                   ItemsSource="{Binding Path = Workers}" 
                   x:Name="DataGrid"/>
  • Code-behind

=

public class Worker    {
        public int Id { get; set; }
        public string Name { get; set; }
    }

public class MainViewModel
{
   public Worker[] Workers        {
            get            {
                return new[]{
                               new Worker {Id = 1, Name = "Cristiano"}, 
                               new Worker {Id = 2, Name = "Lionel"},
                               new Worker {Id = 3, Name = "Xavi"}
                           };
            }
        } ....


Try using a DataSet or DataTable as ItemsSource. Or use ListBox instead.

Also, here is another practice you can try: http://msdn.microsoft.com/en-us/library/system.windows.controls.datagrid.itemssource(VS.95).aspx#Y428

It works for me.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜