2011-12-15 99 views
0

XAML radgrid控件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中沒有數據顯示。

回答

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

如果你能forgoe對具有一個ObserableCollection<T>實例List<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 ......不知道是否有意爲之。

+0

爲什麼我們在這裏使用2個不同的列表(MyObservableList,My List)?我們不能只使用一個列表並將其綁定到radgrids itemssource?謝謝。 – user832219 2011-12-15 20:13:44