RadGrid绑定到列表

时间:2011-12-15 19:20:10

标签: list binding inotifypropertychanged radgrid

XAML RadGrid

<telerik:RadGridView d:DataContext="{d:DesignInstance {x:Type local:A}}" Name="myGridView" Grid.Column="2" ItemsSource="{Binding Path=MyList}"  Margin="7,7,7,2" IsFilteringAllowed="False" ShowColumnHeaders="True" AutoGenerateColumns="True" />

C#代码

Class A:INotifyPropertyChanged
{
 private List<Fields> MyList;
 public event PropertyChangedEventHandler PropertyChanged;
public List<Fields> _theList
{
  get
  {
    if (MyList == null)
    {
      MyList = new List<Fields>();
    }
    return MyList;
  }
  set
  {
    if (MyList != value)
    {
      MyList = value;
      PropertyChanged(this, new PropertyChangedEventArgs("_theList"));
    }
  }
}    
}

当MyList中的项目动态更改时,radgridview不会自动更新,如果我在代码中重置了Itemssource,它会起作用:

mygridview.Itemssource = Null;
mygridview.Itemssource = MyList;

我必须在MyList更改后的代码中每次都重置itemssource。为什么当MyList的内容发生变化时,GridView不会自动更新? 此外,在设计时,它会向我显示列中没有数据的相应列标题,因为列表为空。但是当我运行应用程序时,当MyList的内容动态变化时,列标题会消失,并且radgrid中不会显示任何数据。

1 个答案:

答案 0 :(得分:0)

When the items in MyList change dynamically,

您正在通知列表属性何时更改...这不包括上述方案。为了支持你想要的东西,我认为你需要一个支持INotifyCollectionChanged接口的集合。

http://msdn.microsoft.com/en-us/library/system.collections.specialized.inotifycollectionchanged.aspx

开箱即用,ObservableCollection支持这一点。它来自IList<T>。所以也许你可以这样做:

 private IList<Fields> MyList;
 private IList<Fields> MyObservableList;
 public event PropertyChangedEventHandler PropertyChanged;
public IList<Fields> _theList
{
  get
  {
    if (MyObservableList == null)
    {
      MyObservableList = new ObservableCollection<Fields>();
    }
    return MyObservableList;
  }
  set
  {
    if (MyList != value)
    {
      MyList = value;
      MyObservableList = new ObservableCollection<Fields>(MyList );
      // this will throw a null reference exception if no one' is listening. You 
      PropertyChanged(this, new PropertyChangedEventArgs("_theList"));
    }
  }
}  

如果您可以放弃拥有List<T>个实例的ObserableCollection<T>实例,则上述内容可能会更简单:

   private ObservableCollection<Fields> MyList;
     public event PropertyChangedEventHandler PropertyChanged;
    public ObservableCollection<Fields> _theList
    {
      get
      {
        if (MyList== null)
        {
          MyList= new ObservableCollection<Fields>();
        }
        return MyList;
      }
      set
      {
        if (MyList != value)
        {
          MyList = value;
          // this will throw a null reference exception if no one' is listening. You should make a method OnPropertyChanged that checks if PropertyChanged != null.
          PropertyChanged(this, new PropertyChangedEventArgs("_theList"));
        }
      }
    }

另外,通常情况下,私人成员是_camelCase,公众成员是PascalCase ......不确定是否是故意的。