我有一个数据网格,它绑定到一个collectionviewsource,它绑定到一个observablecollection。在遵循指南的过程中,我将其设置如下:
我的人物课程:
public class Persons : ObservableCollection<Person>
{
//...
}
Run Code Online (Sandbox Code Playgroud)
xaml数据绑定:
<Window.Resources>
<local:Persons x:Key="_Persons"/>
<CollectionViewSource x:Key="cvsPersons" Source="{StaticResource _Persons}" />
</Window.Resources>
Run Code Online (Sandbox Code Playgroud)
数据网格绑定:
<DataGrid x:Name="myDataGrid" ItemsSource="{Binding Source={StaticResource cvsPersons}}"/>
Run Code Online (Sandbox Code Playgroud)
后面的代码:
_Persons = (Persons)this.Resources["_Persons"];
_persons = //some method to fill perons;
cvsPersons = (CollectionViewSource)this.Resources["cvsPersons"];
cvsPersons.Source = _Persons;
Run Code Online (Sandbox Code Playgroud)
以上作品。 我的问题是,为什么我需要在后面使用cvsPersons.Source = _Persons;在代码中设置collectionviewsource.source?我以为我的第一段代码中的xaml可以完成这项工作:
_cvsPersons.Source = _Persons;
Run Code Online (Sandbox Code Playgroud)
如果我需要所有这些代码,那么xaml数据绑定代码似乎没什么用,我也可以在代码中做所有事情。根据我的(也许很少)理解,后面代码中唯一需要的代码是引用xaml设置的实例,即:
_Persons = (Persons)this.Resources["_Persons"];
_persons = //some method to fill perons;
cvsPersons = (CollectionViewSource)this.Resources["cvsPersons"];
Run Code Online (Sandbox Code Playgroud)
如果我没有_cvsPersons.Source = _Persons; 那么我的数据网格将不会被填充。我的xaml不能正常工作。我想我的问题更多与概念有关。